关联容器是通过键存储和读取元素,而顺序容器则是通过元素在容器中的位置顺序存储和访问元素的
关联容器一般包括map、set两种基本的关联容器:
map:适用于需要存储/修改每个键所关联的值的情况
set:希望有效地存储不同值的集合
1)pair的创建和初始化,与顺序容器类似,如下:
pair<string, string> anon; pair<string, int> word_count; pair<string, vector<int>> line; pair<string, string> author("jim", "weshon"); //初始化 typedef pair<string, string> Author; Author product("marcel", "Product");2)pair对象的操作,支持== 、< ,first、second成员的访问,如下
string firstbook; if (author.first == "jim" && author.second == "weshon") { firstbook = "stephon hero"; // }3)生成新的pair对象,如下:
pair<string, string> next_author; string first, second; while (cin >> first >> second) { next_author = make_pair(first, second); //pair<string, string> next_author(first, second); //与上面创建类似 }
1)map对象的定义,支持如下几种:
map<string, int> word_count; map<string, list<size_t>> line_count; map<vector<int>::iterator, int> vcmap; //map<list<int>::iterator, int> lsmap; //error, list can‘t support < operator以上为map<key, value> m; 另外还有如下两种类型
map<key, value> m(m2); //创建m2的副本
map<key, value> m(begin, end); //存储迭代器范围内的所有元素
注意:键类型一定要满足操作符<, 如上list就不支持操作符< ,所以不行
2)map迭代器的使用,如下
map<string, int>::iterator map_iter = word_count.begin(); //iter: pair<const string, int> cout << map_iter->first << " " << map_iter->second << endl; //map_iter->first = "new key"; // error key is const, can‘t copy map_iter->second ++;map的迭代器键类型为const,如上键类型为pair<const string, int>
3)下标访问元素对象,如果不存在,就会创建一个新元素
word_count["jim"] = 1; word_count["sun"] = 1;由于在这两个之前没有元素,所以这两个都会插入为map中的元素,如下使用下标:
cout << "inset map data: key value"<< endl; string word; while (cin >> word) { if (word == "@") break; ++word_count[word]; } map_iter = word_count.begin(); for ( ; map_iter != word_count.end(); ++map_iter) { cout << map_iter->first << " " << map_iter->second << endl; }将重复出现的值+1,新出现的值插入,并将值置为1.
4)map插入元素
。。。
STL之关联容器(pair、map、set的使用),布布扣,bubuko.com
原文:http://blog.csdn.net/comwise/article/details/20078407