map 是键值对的集合,
而 set 容器只是单纯的键 的集合, 没有相关联的值,也就没有 mapped_type 类型
set 不支持下标操作,它的 value_type 不是 pair 类型,而是与 key_type 相同的类型。
set 容器的键也必须唯一,而且不能修改。
当,只想知道一个值是否存在时,用set 容器是最合适的。
vector<int> ivec;
for (vector<int>::size_type i=0; i!=10; ++i)
{
ivec.push_back(i);
ivec.push_back(i);
}
set<int> iset(ivec.begin(), ivec.end());
cout << ivec.size() << endl; // 20
cout << iset.size() << endl; // 10,键,不重复
set<int>::iterator iter;
iter = iset.find(2);
// 解引用, 只读, *iter = 200 将会报错
cout << *iter << endl;
iset.find(1); // 返回相应的迭代器
iset.find(11); // 返回iset.end();
iset.count(1); // 1
iset.count(11); // 0
pair<set<string>::iterator, bool> ret;
set<string> set1;
ret = set1.insert("the");
set1.insert("and");
set<string> set2;
set2.insert(ivec.begin(), ivec.end()); // 返回void
map 和 set 容器中,一个键只能对应一个实例。而 multiset 和 multimap 类型允许一个键对应多个实例。
在 multiset 和 multimap 中,由于键不要求是唯一的,因此每次调用 insert 总会增加一个元素。
map 和 set 的元素是按顺序存储的,multimap 和 multiset 也是一样的。
因此,在 multimap 和 multiset 中,如果某个键对应多个实例,则,这些实例在容器中是相邻存放的。
以上,所说的顺序存储,不是指内存中的连续,
而是指:容器中,按字母顺序依次相邻存放。
multimap<string, string> authors;
authors.insert(make_pair(
string("John"),
string("Spring")));
authors.insert(make_pair(
string("John"),
string("Winter")));
string search_author("John");
typedef multimap<string, string>::size_type sz_type;
sz_type cnt = authors.count(search_author);
// find 返回的是指向第一个该键所关联的元素的迭代器
multimap<string, string>::iterator iter = authors.find(search_author);
for(sz_type i = 0; i!=cnt; ++i, ++iter)
cout << iter->second << endl;
multimap<string, string>::size_type count = authors.erase(search_author);
lower_bound、 upper_bound 操作,
适用于所有的关联容器,包括 map 和 set ,但更常用于 multimap 和 multiset
m.lower_bound(k)
返回一个迭代器,指向键不小于k 的第一个元素
m.upper_bound(k)
返回一个迭代器,指向键大于k 的第一个元素
m.equal_range(k)
返回一个迭代器的 pair 对象
其 first 成员等价于 m.lower_bound(k) ,second 成员等价于 m.upper_bound(k)
对同一个键,调用 lower_bound 和 upper_bound ,将产生一个迭代器范围,指出该键所关联的所有元素。
如果该键存在,
lower_bound 返回的迭代器指向该键关联的第一个实例,
upper_bound返回的迭代器指向该键关联的最后一个实例的下一位置。
如果该键不存在,
两个操作将返回同一个迭代器,指向依据元素排列顺序的情况下,该键应该插入的位置。
如果,所查找的元素拥有 multimap 容器中的最大键(最后一个键),
那么,upper_bound 返回的是超出末端迭代器。
如果,查找的键不存在,而且比 multimap 中的所有键都大,
则,lower_bound 返回的是超出末端迭代器。
typedef multimap<string, string>::iterator author_iter;
author_iter beginIter = authors.lower_bound(search_author),
endIter = authors.upper_bound(search_author);
while(beginIter != endIter)
{
cout << beginIter->second << endl;
++beginIter;
}
继续改写:
typedef multimap<string, string>::iterator author_iter;
pair<author_iter, author_iter> range_iter = authors.equal_range(search_author);
while(range_iter.first != range_iter.second)
{
cout << range_iter.first->second << endl;
++range_iter.first;
}