map是一种关联式容器。
map底层机制是RB-Tree,所以几乎map所有的操作都是调用红黑树的操作。
map的特性是,所有元素都会根据元素的键值自动被排序。map的所有元素那是pair,同时拥有实值(value)和键值(key),**pair的第一元素被视为键值,第二元素被视为实值。**map不允许两个元素拥有相同的键值。
下面是pair的定义:
template <class T1,class T2>
struct pair{
typedef T1 first_type;
typedef T2 second_type;
T1 first;//注意,它是public
T2 second;//注意,它是public
pair(): FirstiTl{)}, second(T2()){}
pair(const T1& a, const.T2& b): first(a), second(b){}
};
我们可以通过map的迭代器改变map的元素内容吗?如果想要修正元素的键值,答案是不行,因为map元素的键值关系到map元素的排列规则。任意改变map元素键值将会严重破坏map组织.但如果想要修正元素的实值,答案是可以,因为map元素的实值并不影响map元素的排列规则。
map拥有和1ist相同的某些性质:当客户端对它进行元素新增操作(insert)或删除操作(crase)时,操作之前的所有迭代器,在操作完成之后都依然有效当然,被删除的那个元素的迭代器必然是个例外。
下面是map的一些基本操作
map<string, int> test;//以string为键值,int为实值。
test["a"] = 1;
test["b"] = 2;
test["c"] = 3;
test["d"] = 4;
pair<string, int> value("e", 5);
test.insert(value);
map<string, int>::iterator it;
for (it = test.begin(); it != test.end(); ++it)
cout << it->first << " " << it->second << endl;
/*查找,关联式容器的查找不要STL的find()函数,它只是顺序查找
而是要用容器自带的find()*/
map<string, int> ::iterator b;
b = test.find("b");
if (b != test.end())
cout << b->first << " " << b->second << endl;
map<string, int>::iterator no;
no = test.find("jlk");
if (no == test.end())
cout << "not find jkl" << endl;
b->second = 9;//通过迭代器修改实值,键值不可以
cout << test["b"] << endl;
输出: