map/multimap关联容器
map/multimap关联容器
容器map/multimap的底层数据结构为红黑树,map是键值对(key-value),每一个元素都有一个键,是排序的基础,每个键只能出现一次,不允许重复,multimap跟map相同,只不过允许重复键,可用来当作字典(单词+意思)。
map
代码
按插入顺序遍历,不排序
#include<iostream>
#include<map>
using namespace std;
typedef map<const char*, int> MapC;
typedef map<const char*, int>::iterator Mit;
int main() {
MapC m;
Mit it;
//三种插入
m.insert(pair<const char *,int>("lily",22));
m.insert(pair<const char*, int>("lucy", 21));
m.insert(map<const char* ,int>::value_type("tom",25));
m["jack"] = 28;
//遍历
for (it = m.begin(); it != m.end();it++) {
cout << "[" << it->first <<","<<it->second << "]" << endl;
}
cout << endl;
//2删除
m.erase("tom");//如果是multimap可以把所有key=tom的都删掉
//查找
it = m.find("lucy");
if(it!=m.end()){
m.erase(it);
}
//遍历
for (it = m.begin(); it != m.end(); it++) {
cout << "[" << it->first << "," << it->second << "]" << endl;
}
m.clear();
if (m.empty())
cout << "map is empty" << endl;
}
加上比较谓词自动排序遍历
//比较谓词
//从小到大排序
struct Itstr {
bool operator()(const char* s1, const char* s2)const {
return strcmp(s1, s2) < 0;
}
};
typedef map<const char*, int, Itstr> MapC;
typedef map<const char*, int, Itstr>::iterator Mit;
multimap允许关键字重复
typedef multimap<const char*, int, Itstr> MapC;
typedef multimap<const char*, int, Itstr>::iterator Mit;
//2种插入
m.insert(pair<const char *,int>("lily",22));
m.insert(pair<const char*, int>("lily", 23));
m.insert(pair<const char*, int>("lucy", 21));
m.insert(multimap<const char* ,int>::value_type("tom",25));
m.insert(multimap<const char*, int>::value_type("tom", 27));
//m["jack"] = 28;
注意
- cout << “[” << it->first <<","<second << “]” << endl;
- 不会自动排序;可以自行添加比较谓词。
- map有3种插入方法,multimap有2种插入方法。
- mutimap支持重复关键字。