c++ STL 容器——联合容器

STL提供了四种联合容器 set,multiset,map,multimap;

set and multiset在<set>头文件

map and multimap在<map>头文件

模板函数都一样的http://www.cnblogs.com/jinmingyi/p/6798359.html

set/map中迭代器不能++或--,因为不是连续的序列,是树。

set:

在set中,值就是关键字,集合中不会有多个相同的关键字,且始终按从小到大的顺序排列

可反转可排序,关键字是唯一的,只能存储同一个类型的值

 1 #include<iostream>
 2 #include<set>
 3 using namespace std;
 4 void update(set<int>&s,set<int>::iterator it,int i)
 5 {
 6     int x = *it;        //使x保存当前迭代器指向的数值
 7     x += i;                //x更改为需要的数值
 8     s.erase(*it);        //删除set中迭代器指向的数值*it
 9     s.insert(x);        //将新的x插入set
10 }
11 int main()
12 {
13     set<int>s;            //声明一个set
14     for (int i = 0; i < 10; i++)
15     {
16         s.insert(i);    //向set中插入数值
17     }
18     set<int>::iterator it;
19     int i;
20     if (s.find(2) == s.end())
21         cout << "no 2" << endl;
22     else
23         cout << "yes" << endl;
24     for (i=0,it = s.begin(); it != s.end(); i++)
25     {
26         update(s,it, i);    //不能对set中已有的数值操作  自己写个更新函数
27         it = s.find(i);
28     }
29 }

map:

map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的

声明一个map: map<下标的类型,对应数据的类型>name;

 1 #include<map>
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 int main()
 6 {
 7     map<string, int>mp;    //声明一个map
 8     mp["abc"] = 1;        //向map中添加一个数据
 9     map<string, int>::iterator it;//声明一个迭代器
10     it = mp.find("aaa");//find函数返回一个迭代器,找到返回对应迭代器,否则返回end()
11     if (it == mp.end())
12         cout << "no" << endl;
13 }

还有这两个都可以用lowet_bound()  (大于等于的第一个)和upper_bound()  (绝对大于的第一个,双写p!)  返回的都是迭代器。

写博中发现一个细节:迭代器it对应的元素被删掉了,就不能在it++或it--;

如果

原文地址:https://www.cnblogs.com/jinmingyi/p/6803718.html