STL源码解析-05关联容器-01map&set
关联容器主要包括,map,set,multimap,multiset,器底层实现都是rb树。
sgi stl还提供了,hash_map,hash_set,hash_multimap,hash_multiset,其底层实现都是hash table。
对关联容器进行查找时,最好使用容器自带的函数。
*********************************************
* map,内部也是红黑树。
* 删除增加元素后,迭代器依然有效。
* multimap与map还有的方法一样,唯一不同就是允许建重复。
* *************************************/
/*******************************************
* 关于insert和[]
* insert之后,返回一个pair<iterator, bool>。
* []作为左值时,如果元素存在,覆盖,不存在插入。
* []作为右值时,返回。
* 其实现是这样的,返回值是一个引用,调用insert函数。
* return ( *(( insert(value_type(k,t)) ).first) ).second;
* ********************************************
********************************************************
* set,里面全部是主键,不能修改。
* 完成删除等操作后,迭代器依然有效。
* multiset与set一样,唯一不同就是允许键重复。
* ******************************************************
#include <set>
#include <iostream>
using namespace std;
int main()
{
int ia[5] = {1,2,3,4,5};
set<int> iset(ia, ia+5);//初始化已经排序
cout << "size:" <<iset.size() << endl;
cout << "3 count=" << iset.count(3);
iset.insert(3);
cout << "size:" <<iset.size() << endl;
cout << "3 count=" << iset.count(3);//不能插入相同的元素
iset.erase(4);
cout << "size:" <<iset.size() << endl;
cout << "3 count=" << iset.count(3) << endl;
set<int>::iterator ib = iset.begin();//可以使用迭代器
set<int>::iterator ie = iset.end();
ib = iset.find(3);//最好调用容器本身的find,而不是算法中的find。
if (ib != ie)
cout << "3 found\n";
ib = iset.lower_bound(2);//2的位置
ie = iset.upper_bound(4);//大于4的位置
//*ib = 65;//wrong
return 0;
}
浙公网安备 33010602011771号