这四种关联式容器可以分成两组:set和map。
set是一种集合,其中可包含0个或多个不重复的和不排序的元素,然后默认从小到大排序输出。
(若要从大到小排:创建实例set<int,greater<int>>iset;)
multiset是容许有重复键值的set。
begin(),返回set容器的第一个元素
end() ,返回set容器的最后一个元素
clear(),删除set容器中的所有的元素
insert(key_value); 将key_value插入到set中 ,返回值是pair<set<int>::iterator,bool>,bool标志着插入是否成功,而iterator代表插入的位置,若key_value已经在set中,则iterator表示的key_value在set中的位置。
inset(first,second);将定位器first到second之间的元素插入到set中,返回值是void.
empty() ,判断set容器是否为空
find() ,返回给定值值得定位器,如果没找到则返回end()。
max_size(),返回set容器可能包含的元素最大个数
size() ,返回当前set容器中的元素个数
rbegin ,返回的值和end()相同
rend() ,返回的值和rbegin()相同
equal_range() ,返回一对定位器,分别表示第一个大于或等于给定关键值的元素和 第一个大于给定关键值的元素,这个返回值是一个pair类型,如果这一对定位器中哪个返回失败,就会等于end()的值。
erase(iterator) ,删除定位器iterator指向的值
erase(first,second),删除定位器first和second之间的值
erase(key_value),删除键值key_value的值
lower_bound(key_value) ,返回第一个大于等于key_value的定位器
upper_bound(key_value),返回最后一个大于等于key_value的定位器
可参考例题:TOJ 1283
#include <iostream>
#include <set>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n,m,a;
cin >> n;
while (n--)
{
cin >> m;
multiset<int>s;
while (m--)
{
cin >> a;
s.insert(a);
}
set<int>::iterator it;
it = s.begin();
cout << *it;
*it++;
for (;it!=s.end();it++)
cout << " "<< *it;
cout << endl;
}
}
map是一种集合,其中可包含0个或多个不排序的元素对,一个元素是不重复的键值,另一个是与键值相关联的值。
multimap是容许有重复键值的map。
头文件#include<map>
创建实例:map<string,int>m;
m["zero"]=0;//string类型“zero”对应int类型0
cout<<m[“zero"]<<endl;//此时输出的是0
可参考例题:TOJ 1351
#include <iostream>
#include <map>
#include <string>
#include <sstream>
using namespace std;
int main()
{
map<string, int>m;
string s;
while (getline(cin,s))
{
if (s == "#")break;
stringstream ss(s);
string b;
while (ss>>b)
{
m[b] = 1;
}
cout << m.size() << endl;
m.clear();
}
}
推荐一个map详解:http://blog.csdn.net/nwf5d/article/details/4338872