map、multimap容器
简介:map中所有元素都是pair
pair中第一个元素为key(键值),第二个元素为value(实值)
所有元素都会根据元素的键值自动排序
本质:map、multimap属于关联式容器,底层结构用二叉树实现
优点:可以用key值快速找到value值
map与multimap区别:map不允许容器中有重复key值元素;multimap允许重复key值元素
1.map构造和赋值
#include <iostream>
#include <string>
#include <map>
using namespace std;
void printmap(map<int,int>&s){
for(map<int,int>::iterator it=s.begin();it!=s.end();it++){
cout<<(*it).first<<" "<<it->second<<endl;
}
cout<<endl;
}
void test01(){
map<int,int>m;
m.insert(pair<int,int>(1,10));
m.insert(pair<int,int>(4,40));
m.insert(pair<int,int>(2,20));
m.insert(pair<int,int>(3,30));
printmap(m);
//拷贝构造
map<int,int>m2(m);
printmap(m2);
//赋值
map<int,int>m3;
m3=m2;
printmap(m3);
}
int main(){
test01();
}
2.map大小和交换
#include <iostream>
#include <string>
#include <map>
using namespace std;
void printmap(map<int,int>&s){
for(map<int,int>::iterator it=s.begin();it!=s.end();it++){
cout<<(*it).first<<" "<<it->second<<endl;
}
cout<<endl;
}
void test01(){
map<int,int>m1;
m1.insert(pair<int,int>(1,100));
m1.insert(pair<int,int>(2,300));
if(m1.empty())
cout<<"empty"<<endl;
else
cout<<"no empty"<<endl;
map<int,int>m2;
m2.insert(pair<int,int>(5,6000));
m2.insert(pair<int,int>(5,1500));
m2.insert(pair<int,int>(4,1800));
printmap(m1);
printmap(m2);
m1.swap(m2);
printmap(m1);
printmap(m2);
}
int main(){
test01();
}
3.map容器插入和删除
#include <iostream>
#include <string>
#include <map>
using namespace std;
void printmap(map<int,int>&s){
for(map<int,int>::iterator it=s.begin();it!=s.end();it++){
cout<<(*it).first<<" "<<it->second<<endl;
}
cout<<endl;
}
void test01(){
map<int,int>m;
//4种插入方式
m.insert(pair<int,int>(1,10));
m.insert(make_pair(2,20));
m.insert(map<int,int>::value_type(3,30));
m[4]=40;//[]不建议插入,用途可以利用key访问到value
printmap(m);
//删除
m.erase(m.begin());
m.erase(2);//按照key删除
printmap(m);
m.erase(m.begin(),m.end());
m.clear();
}
int main(){
test01();
}
4.map查找和统计
#include <iostream>
#include <string>
#include <map>
using namespace std;
void test01(){
map<int,int>m;
m.insert(pair<int,int>(1,10));
m.insert(make_pair(2,20));
m.insert(map<int,int>::value_type(3,30));
m.insert(map<int,int>::value_type(3,550));
m.insert(map<int,int>::value_type(3,3440));
//查找
map<int,int>::iterator pos=m.find(3);
if(pos!=m.end())
cout<<"find"<<" "<<(*pos).first<<" "<<(*pos).second<<endl;
else
cout<<"miss"<<endl;
//统计
//map不允许插入重复key元素
int num=m.count(3);
cout<<num<<endl;
}
int main(){
test01();
}
5.map容器排序
利用仿函数,改变排序规则
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Comapre{
public:
bool operator()(int v1,int v2){
return v1>v2;
}
};
void printmap(map<int,int,Comapre>&s){
for(map<int,int,Comapre>::iterator it=s.begin();it!=s.end();it++){
cout<<(*it).first<<" "<<it->second<<endl;
}
cout<<endl;
}
void test01(){
map<int,int,Comapre>m;
m.insert(pair<int,int>(1,10));
m.insert(make_pair(2,20));
m.insert(map<int,int,Comapre>::value_type(3,30));
printmap(m);
}
int main(){
test01();
}
unordered_map的本质是哈希表,是无序的,查询、增删的效率是最高的