简介
关联式容器通常由二叉树实现出来。而且每个节点都有一个父节点和两个子节点;左子树的所有元素都比自己小,右子树的所有元素都比自己大。关联式容器主要差别在于元素的种类以及处理重复元素时的方式。
优势是快速查出某特定value的值,具备对数复杂度,劣势是不能直接改变value的值,那会破坏元素的自动排序。
Set
元素依据其value自动排序,每个元素出现一次,不重复。
Multiset
和set的唯一差别是:元素可以重复。也就是mulset可包含多个“value” 相同的元素。
Map
每个元素都是 key/value pair ,其中key是排序准则的基准。每个key只能出现一次,不允许重复。Map也可视作关联型数组,也就是引用可为任意类型的数组。
Multimap
和map唯一的区别是:元素可以重复,也就是multimap允许其元素拥有相同的key。multimap可当做字典使用。
set的基本操作:
#include<iostream>
#include<set>
#include<string>
using namespace std;
int main()
{
multiset<string> cities
{
"beijing","wuhan","zhengzhou","newyork","paris","toronto","beijing"
};
for (auto elem : cities)
{
cout << elem << " ";
}
cities.insert({ "london", "hanover" });
cout << endl;
for (auto elem : cities)
{
cout << elem << " ";
}
cout << endl;
system("pause");
}
map的基本操作:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
multimap<int, string> coll;
coll = {
{ 5,"tagged" },
{ 2, "a" },
{ 1,"this" },
{ 4,"of" },
{ 6,"strings" },
{ 1,"is" },
{ 3,"multimap" }
};
for (auto elem : coll)
{
cout << elem.second << ' ';
}
cout << endl;
system("pause");
}