您的位置:首页 > 编程语言 > C语言/C++

C++primer第4版第十章关联容器

2016-12-06 20:36 155 查看
Talk is cheap, show me the code.

使用pair对象必须包含头文件utility,创建pair对象有多中方式:

pair<string, int> p;

p.first = "hello";

p.second = 12;

pair<string, int> p1("hello", 12);

pair<string, int> p2 = make_pair("hello", 12);


使用map对象必须包含头文件map,而且作为key的类型必须定义了 < 运算操作;

不能使用map的下标操作来判断一个key是否存在于map中,而应当用find或者count函数来判断,因为下标操作即使元素不存在也会创建一个元素,并置为初始值。优先选择find函数来查找。

map<string, int> map1;

map<string, int>::iterator it = map1.find("hello");  //找到就返回该元素的迭代器,没找到就返回map1.end()迭代器

int count = map1.count("hello");   //对于map来说只能返回0 或者 1


map的常用操作有:insert(key),map[key]=value,erase(key),find(key),count(key)等等。

使用set对象必须包含头文件set,set中的元素类型都是const,不能修改,而且都不重复。set常用操作有:insert(key),erase(key),find(key),count(key)等等。

set头文件中还有multiset,map头文件中还有multimap,都支持多个相同key的元素,这些相同key的元素都相邻存放。需要访问时提供了起始和终止下一位置的迭代器,这时候count()函数就体现出它的意义。

multiset<string> ms;

ms.insert("hello");

ms.insert("hello");

multiset<string>::iterator beg = ms.lower_bound("hello");

multiset<string>::iterator end = ms.upper_bound("hello");

while (beg != end)

{

cout << *beg++ << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++primer