STL容器-set、map、multiset、multimap(源自STL源码剖析)

1.set概述

  set的特性是,所有元素都会根据元素的键值自动被排序。set的元素不像map那样可以同时拥有实值(value)和键值(key),set元素的键值就是实值,实值就是键值。set不允许两个元素有相同的键值。

  由于RB-tree(红黑树)是一种平衡二叉搜索树,自动排序的效果很不错,所以标准的STL,set即以RB-tree为底层机制

  我们可以通过 set 的迭代器改变 set 的元素值吗?不行,因为 set 元素值就是其键值,关系到set元素的排列规则。如果任意改变 set 元素值,会严重破坏 set 组织。稍后你会在 set 源代码之中看到,set::iterator被定义为底层 RB-tree 的 const_iterator ,杜绝写入操作。换句话说,set iterators是一种constant iterators(相对于mutable iterators)。


//  使用STL算法 find()来搜寻元素,可以有效运作,但不是好办法
ite1 = find(iset.begin(),  iset.end(),  3);
if (itel != iset.end())
        cout << "3 found" << endl;                        // 3 found

ite1 = find(iset.begin(),  iset.end(),  1);
if (ite1 == iset.end())
        cout << "1 not found" << endl;                 // 1 not found

//  面对关联式容器,应该使用其所提供的find函数来搜寻元素,会比
//  使用STL算法find()更有效率。因为STL算法find()只是循序搜寻

ite1 = iset.find(3);
if (itel != iset.end())
        cout << "3 found" << endl;                        // 3 found

ite1 = iset.find(1);
if (itel == iset.end())
        cout << "1 not found" << endl;                 // 1 not found

//企图通过迭代器来改变set元素,是不被允许的
*itel = 9;                 // error, assignment of read-only location

2.map概述

  map的特性是,所有元素都会根据元素的键值自动被排序。map的所有元素都是pair,同时拥有实值  (value)和键值(key)。pair的第一元素被视为键值,第二元素被视为实值。map不允许两个元素拥有相同的键值。

  我们可以通过map的迭代器改变map的元素内容吗?如果想要修正元素的键值,答案是不行,因为map元素的键值关系到map元素的排列规则。任意改变map元素键值将会严重破坏map组织。但如果想要修正元素的实值,答案是可以,因为map元素的实值并不影响map元素的排列规则。因此,map iterators既不是一种constant iterators,也不是一种mutable iterators。

  由于 RB-tree 是一种平衡二叉搜索树,自动排序的效果很不错,所以标准的STL map即以 RB-tree为底层机制。


//  面对关联式容器,应该使用其所提供的find函数来搜寻元素,会比
//  使用STL算法find()更有效率。因为STL算法find()只是循序搜寻
ite1 = simap.find(string("mchen") );
if (itel == simap.end())
        cout <<  "mchen not found"  << endl;       // mchen not found

ite1 = simap.find(string("jerry") );
if (itel != simap.end())
        cout <<  "jerry found"  << endl;                 // jerry found

itel->second= 9;                                                  //  可以通过map迭代器修改"value"(not key)
int number2 = simap[string("jerry") ];
cout << number2 << endl;                                  //  9

3.multiset

  multiset 的特性以及用法和 set 完全相同,唯一的差别在于它允许键值重复,因此它的插人操作采用的是底层机制 RB-tree 的 insert_equal()而非insert_unique()。

4.multimap

  multimap 的特性以及用法与 map 完全相同,唯一的差别在于它允许键值重复,因此它的插人操作采用的是底层机制 RB-tree 的 insert_equal() 而非 insert_unique() 。

你可能感兴趣的:(c++,开发语言)