map的用法以及可能会犯的错误
1.插入操作与赋值操作(size与empty用法)
#include<map>
#include<iostream>
using namespace std;
int main() {
map<int, string>m1;
m1[4] = "大哥";//也可以用at()但这两种不能混用会报错
m1.insert(make_pair<int, string>(0, "张三"));
m1.insert(make_pair<int, string>(1, "李四"));
m1.insert(make_pair<int, string>(2, "王五"));
m1.insert(make_pair<int, string>(3, "赵六"));
for (map<int, string>::iterator it = m1.begin(); it != m1.end(); it++) {
cout << "Key键:" << (*it).first<<" " << "value值:" << (*it).second;
cout << endl;
}
cout << "长度" << m1.size() << endl;
cout << "是否为空" << m1.empty();
cout << endl;
}
2.删除与清空操作
m1.clear();
m1.erase(m1.begin());//仅仅做演示不能连用的
3.查找操作
#include<map>
#include<iostream>
using namespace std;
int main() {
map<int, string>m1;
m1[4] = "大哥";
m1.insert(make_pair<int, string>(0, "张三"));
m1.insert(make_pair<int, string>(1, "李四"));
m1.insert(make_pair<int, string>(2, "王五"));
m1.insert(make_pair<int, string>(3, "赵六"));
for (map<int, string>::iterator it = m1.begin(); it != m1.end(); it++) {
cout << "键:" << (*it).first<<" " << "值:" << (*it).second;
cout << endl;
}
cout << "长度" << m1.size() << endl;
cout << "是否为空" << m1.empty();
cout << endl;
map<int,string>::iterator it=m1.find(1);
cout << (*it).second;
cout << endl;
}
4.逆序操作
#include<map>
#include<iostream>
using namespace std;
int main() {
map<int, string,greater<int>>m1;//未指定默认less
m1[4] = "大哥";
m1.insert(make_pair<int, string>(0, "张三"));
m1.insert(make_pair<int, string>(1, "李四"));
m1.insert(make_pair<int, string>(2, "王五"));
m1.insert(make_pair<int, string>(3, "赵六"));
for (map<int, string,greater<int>>::iterator it = m1.begin(); it != m1.end(); it++) {
cout << "键:" << (*it).first<<" " << "值:" << (*it).second;
cout << endl;
}
cout << "长度" << m1.size() << endl;
cout << "是否为空" << m1.empty();
cout << endl;
map<int,string>::iterator it=m1.find(1);
cout << (*it).second;
cout << endl;
}