关联容器

来源:互联网 发布:马蓉出轨的代价 知乎 编辑:程序博客网 时间:2024/06/04 23:22
一:基本介绍
关联容器与顺序容器有根本不同。关联容器的元素是按照关键字来保存和访问的。然而,顺序容器中的元素是按照他们在容器中的位置来顺序保存和访问的。看关联容器中最常用的两个容器就好理解了,(Set、Map),他们都用key-value来保存的。
关联容器类型如下:
1.map
2.set
3.multimap
4.multiset
5.unordered_map
6.unordered_set
7.unordered_multimap
8.unordered_multiset
从上面的8个容器的命名可以容易看出来,容器之间的区别不外乎3个:
(一)要么是一个map,要么是一个set
(二)有重复的关键字,要么不允许重复的关键字
(三)按顺序保存元素,要么做无序保存
:使用关联容器

find()函数:用来查找某个key是否存在,它返回一个迭代器。如果存在,那么迭代器指向该关键字,如果不存在,则返回尾后迭代器。看例子:


有一个需要注意的地方,看如下代码:
#include <map>#include <string>#include <iostream>using namespace std;map<int, string> mapStudent;int main() {    mapStudent.insert(pair<int, string>(3, "student_one"));    mapStudent.insert(pair<int, string>(3, "student_tw"));    mapStudent.insert(pair<int, string>(3, "student_three"));    map<int, string>::iterator  iter;    iter = mapStudent.find(3);    printf("%s\n", iter->second.c_str());    return 0;}
      执行结果是:student_one
具体原因如下:
Because element keys in a map are unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value).

insert时相同的key不会被覆盖,但是下标访问表达式,map[key] =value;这样的调用是会被重写相应key的值的。


三:pair类型
例如:pair<string, string> author{"james", "Joyce"};
访问的时候可以用如下:
cout<<author.first<<author.second<<endl;

pair的数据成员是public的,pair一般用来表示map中的某个元素。
在构造pair时候,还可以用make_pair函数,如:

pair<string, int> my_pair = make_pair(v.back(),  v.back().size());

值得注意的细节:
1.auto map_it = word_count.begin();// *map_it 是指向一个pair<const string, size_t>对象的引用
map_it->first是const的,不可改变,但是map_it->second可以改变。
2.set的迭代器是const的,看如下代码:
set<int> iset = {0,1,2,3};set<int>::iterator set_it = iset.begin();if(set_it != iset.end()) {    *set_it = 42;           //错误:set中的关键字是只读的    cout << *set_it << endl;//正确:可读关键字}
     3.遍历关联容器
auto map_it != word_count.cbegin();while(map_it != word_count.cend()) {    cout << map_it->first << map_it->second << endl;    ++map_it;//递增迭代器,移动到下一个元素}/*c开头的是C++11的,新标准,区别是:begin():Return iterator to beginning (public member function )cbegin():Return const_iterator to beginning (public member function )*/




0 0