/*标准模板库(stl)之映射(map)
*map提供一对一映射,其中第一个键值为主键,不能重复
*map按照主键自动排序
*/
#include <iostream>
#include <map>
using namespace std;
int main()
{
//定义模板类对象并插入元素
map<string, string> words;
words.insert(pair<string,string>("friend", "朋友"));
words.insert({"good", "非常好"});
pair<string,string> a("and", "并且");//定义一个pair对象插入map
words.insert(a);
words.insert({"good", "好"});
words["you"] = "你";//如果有无此映射则添加,如果有则改变
words["friend"] = "哥们";
cout << "查看 good : " << words["good"] << endl;
cout << "查看 yes : " << words["yes"] << endl;//这里没有yes这个key,所以返回为空
//使用迭代器遍历
cout << "--------------" << endl;
for (auto it=words.begin(); it!=words.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
//使用迭代器遍历
map<string ,string>::iterator it = words.find("good");
if (it != words.end()) {
cout << "map is : " << it->second << endl;
} else {
cout << "没找到" << endl;
}
}
*map提供一对一映射,其中第一个键值为主键,不能重复
*map按照主键自动排序
*/
#include <iostream>
#include <map>
using namespace std;
int main()
{
//定义模板类对象并插入元素
map<string, string> words;
words.insert(pair<string,string>("friend", "朋友"));
words.insert({"good", "非常好"});
pair<string,string> a("and", "并且");//定义一个pair对象插入map
words.insert(a);
words.insert({"good", "好"});
words["you"] = "你";//如果有无此映射则添加,如果有则改变
words["friend"] = "哥们";
cout << "查看 good : " << words["good"] << endl;
cout << "查看 yes : " << words["yes"] << endl;//这里没有yes这个key,所以返回为空
//使用迭代器遍历
cout << "--------------" << endl;
for (auto it=words.begin(); it!=words.end(); it++) {
cout << it->first << " : " << it->second << endl;
}
//使用迭代器遍历
map<string ,string>::iterator it = words.find("good");
if (it != words.end()) {
cout << "map is : " << it->second << endl;
} else {
cout << "没找到" << endl;
}
}