关联容器关联容器将值与键关联在一起,并使用键来查找值。关联容器的优点在于,它提供了对元素的快速访问。
1.关联容器允许插入新元素,但不能指定元素插入的位置。
2.关联容器使用某种树实现的。
STL(标准模板库)提供了四种关联容器:set、multiset、map和multimap
一、set关联容器
set关联容器:它是关联集合,可反转,可排序,且键是唯一的,所以不能存储多个相同的值。
demon
#include<iostream>
#include<string>
#include<set>
#include<algorithm>
#include<iterator>
int main()
{
using namespace std;
const int N = 6;
string s1[N] = { "one","two","three","four","five","A" };
string s2[N] = { "six","seven","eight","nine","ten","A"};
set<string> A(s1,s1 + N );
set<string> B(s2,s2 + N );
ostream_iterator<string,char> out(cout," ");
cout << "Set A: ";
copy(A.begin(), A.end(), out);
cout << endl;
cout << "Set B: ";
copy(B.begin(),B.end(),out);
cout << endl<< endl;
cout << "合并Union of A and B :\n";
set_union(A.begin(),A.end(),B.begin(),B.end(),out);//有序合并去重
cout << endl<< endl;
cout << "交集Intersection of A and B:\n";
set_intersection(A.begin(),A.end(),B.begin(),B.end(),out);//A,B交集
cout << endl<< endl;
cout << "不同Difference of A and B :\n";
set_difference(A.begin(),A.end(),B.begin(),B.end(),out);//A相对于B的不同
cout << endl<< endl;
set<string> C;
cout << "Set C:\n";
set_union(A.begin(),A.end(),B.begin(),B.end(),insert_iterator<set<string> >(C,C.begin()));
copy(C.begin(),C.end(),out);
cout<<endl<< endl;
string s3("grungy");
C.insert(s3);
cout << "Set C after insertion:\n";
copy(C.begin(),C.end(),out);
cout << endl<< endl;
cout << "Showing a range:\n";
copy(C.lower_bound("ghost"),C.upper_bound("spook"),out);//返回不小于ghost和不大于spook的元素
cout << endl;
return 0;
}
运行结果:
二、multimap关联容器
multimap关联容器:可反转、经过排序的关联容器,键和值的类型不同,且一个键可能与多个值相关联。
demon
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
typedef int KeyType;
typedef std::pair<const KeyType,std::string> Pair;
typedef std::multimap<KeyType,std::string> MapCode;
int main()
{
using namespace std;
MapCode codes;
codes.insert(Pair(416,"San Francisco"));
codes.insert(Pair(510,"Oakland"));
codes.insert(Pair(718,"Brooklyn"));
codes.insert(Pair(718,"Staten Island"));
codes.insert(Pair(415,"San Rafael"));
codes.insert(Pair(510,"Berkeley"));
cout << "Number of cities with area code 415: "
<< codes.count(415) << endl; //统计键值为415的数量
cout << "Number of cities with area code 718: "
<< codes.count(718) << endl;
cout << "Number of cities with area code 510: "
<< codes.count(510) << endl;
cout << "Area Code City\n";
MapCode::iterator it;
for(it = codes.begin(); it != codes.end();++it)
cout << " " << (*it).first << " " << (*it).second << endl;
pair<MapCode::iterator,MapCode::iterator> range = codes.equal_range(718);//返回键值为718的到range
cout << "Cities with area code 718:\n";
for(it = range.first; it != range.second; ++it)
cout << (*it).second << endl;
return 0;
}
运行结果: