1.map和multimap是键-值对容器。可以根据键查找。map只能是唯一的键,multimap可以存在重复的键
2.map和multimap内部结构和二叉树差不多。插入元素的时候要进行排序。这样查找起来更加迅速。不过不可以像vector那样找到一个元素的位置,进行替换,因为数据是需要排序的。
3.模版需要包含<map>头文件
4.创建
map<int, string> a;
multimap<int, string> b;
第一个是key,第二个是value,还有一个参数可选谓词,用来排序。指明就用默认的
5.插入元素
#include <map>
#include <isotream>
using namespace std;
int main(){
map<int, string> a;
a.insert(map<int, string>::value_type(3, "three"));
a.insert(make_pair(-1, "minus one"));
a.insert(pair<int, string>(1000, "one thousand"));
a[10] = "ten";
map<int, string>::const_iterator i;
for(i = a.begin(); i!=a.end(); ++i){
cout <<"key: "<<i->first;
cout<< " value: "<<i->second.c_str();
cout << endl;
}
multimap<int, string> a;
b.insert(multimap<int, string>::value_type(3,"three"));
b.insert(multimap<int, string>::value_type(45, "forty five"));
b.insert(make_pair(-1, "minus one"));
b.insert(pair<int, string>(1000, "one thousand"));
b.insert(multimap<int, string>::value_type(1000,"thousand"));
multimap<int, string>::const_iterator j;
for(j=b.begin(); j!=b.end(); ++j){
cout<<j->first<<j->second.c_str();
}
cout<<"the number of pairs in the multimap with 1000 as their key: " << b.count(1000)<<endl;
return 0;
}
6.删除元素
multimap<int, string> a;
a.insert...
a.erase(2);//删除a中所有key为2的元素
multimap<int, string>::iterator i;
i=a.find(34);
a.erase(i);//找到a中的34,然后删除
a.erase(a.lower_bound(2), a.upper_bound(0));//删除a中大于0小于2的元素
在删除的时候传递给erase的迭代器不要const_iterator,因为我们需要改变,所以用iterator
7.提供自定义排序谓词
#include<map>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
struct cc{
bool operator()(const string & str1, const string & str2)const{
string str1no(str1), str2no(str2);
transform(str1.begin(), str1.end(), str1no.begin(), tolower);
transform(str2.begin(), str2.end(), str2no.begin(), tolower);
return (str1no<str2no);
};
};
int main(){
map<string, string, cc> a;
a.insert(map<string, string, cc>::value_type("john", "23423"));
a.insert(map<string, string, cc>::value_type("JOHN", "23423"));
a.insert(map<string, string, cc>::value_type("sara", "234"));
a.insert(map<string, string, cc>::value_type("jack", "45345"));
map<string, string, cc>::const_iterator i;
for(i=a.begin(); i!=a.end(); i++){
cout<<i->first<<i->second;
}
map<string, string, cc>::iterator i = a.find("JOhn");
return 0;
}
调用find函数时,由于我们定义了一个谓词,来实现()方法,所以不区分大小写,能够找到
8.map<int, less<int>>这是降序,默认的
map<int, greater<int>>这是升序