本文介绍STL中的关联容器的内容。
关联容器中的元素根据一些排序规则自动进行排序的。缺省的排序规则是关系运算符 <(小于)。用户也可以指定自己的排序规则选项。
因为关联容器中的元素是自动排序的,因此,当一个新的元素插入到容器中时,它插入到容器中适当的位置。一种方便和快速的实现该类数据结构的方式是使用二叉搜索树。实际上这就是关联容器实现的方式。因此,容器中每个元素有一个父节点(除了根结点),同时最多有两个孩子,对于各个元素,父节点的key大于左孩子的key,同时小于右孩子的key。
STL中预定义的关联容器如下:
#include <set>
set<int> intSet; //Line 1 set<int, greater<int> > otherIntSet; //Line 2 multiset<string> stringMultiSet; //Line 3 multiset<string, greater<string> > otherStringMultiset; //Line 4
#include <iostream> #include <set> #include <string> #include <iterator> #include <algorithm> using namespace std; int main() { set<int> intSet; set<int, greater<int> > intSetA; set<int, greater<int> >::iterator intGtIt; ostream_iterator<int> screen(cout, " "); intSet.insert(16); intSet.insert(8); intSet.insert(20); intSet.insert(3); cout << "intSet: "; copy(intSet.begin(), intSet.end(), screen); cout << endl; cout << "==================================================" << endl; intSetA.insert(36); intSetA.insert(84); intSetA.insert(30); intSetA.insert(39); intSetA.insert(59); intSetA.insert(238); intSetA.insert(156); cout << "intSetA:"; copy(intSetA.begin(), intSetA.end(), screen); cout << endl; cout << "==================================================" << endl; intSetA.erase(59); cout << "After removing 59,intSetA: "; copy(intSetA.begin(), intSetA.end(), screen); cout << endl; cout << "==================================================" << endl; intGtIt=intSetA.begin(); ++intGtIt; ++intGtIt; ++intGtIt; intSetA.erase(intGtIt); cout << "After removing the fourth " << "element," << endl << " intSetA: "; copy(intSetA.begin(),intSetA.end(),screen); cout<<endl; cout << "==================================================" << endl; set<int,greater<int> > intSetB(intSetA); cout << "intSetB:"; copy(intSetB.begin(), intSetB.end(), screen); cout << endl; cout << "==================================================" << endl; intSetB.clear(); cout<<"After removing all elements," << endl << " intSetB: "; copy(intSetB.begin(), intSetB.end(), screen); cout << endl; cout << "==================================================" << endl; multiset<string, greater<string> > namesMultiSet; multiset<string, greater<string> >::iterator iter; ostream_iterator<string> pScreen(cout, " "); namesMultiSet.insert("Donny"); namesMultiSet.insert("Zippy"); namesMultiSet.insert("Goofy"); namesMultiSet.insert("Hungry"); namesMultiSet.insert("Goofy"); namesMultiSet.insert("Donny"); cout << "namesMultiSet: "; copy(namesMultiSet.begin(), namesMultiSet.end(), pScreen); cout << endl; cout << "==================================================" << endl; return 0; }