map方法总结
map提供一对一的hash,采用key——value键值对,可以是任意类型(包括自定义类型)
头文件
#include<map>
定义一个map对象
map<int,string> mapStudent;
插入数据——数组方式,若已存在键,会覆盖
mapStudent[1] = “student_one”;
插入数据——pair方式,若已存在键,插入失败
pair<map<int, string>::iterator, bool> ret;
ret = mapStudent.insert(pair<int, string>(1, “student_two”));
ret.first ⇒ 1
ret.second ⇒ false (已存在1这个键,返回false)
ret.first -> second ⇒ student_one (本身键的值)
迭代器遍历
map<int,string> ::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
cout << iter->first << ’ ’ << iter->second << end;
map大小
int size = mapStudent.size();
是否存在某键,存在返回1,否则0
int n = mapStudent.count(1);
查找数据
1⃣️直接cout << mapStudent[1]
2⃣️find() 找到则返回指向该关键字的迭代器,否则返回指向end的迭代器
map<int,string> ::iterator iter;
iter = mapStudent.find(1);
if(iter != mapStudent.end())
cout << “Find” << iter->second << endl;
删除元素
1⃣️迭代器删除
map<int,string> ::iterator iter;
iter = mapStudent.find(1);
mapStudent.erase(iter);
2⃣️关键字删除
int n = mapStudent.erase(1); 删除返回1,否则返回0
3⃣️成片删除(前闭后开)
mapStudent.erase(mapStudent.begin(), mapStudent.end());
相当于清空
mapStudent.clear();
排序
默认按键升序排列,因此map是有序的
1⃣️对有序map中的key自定义排序,如按字符串长度
struct CmpByKeyLength {
bool operator()(const string& k1, const string& k2)const {
return k1.length() < k2.length();
}
};
map<string, int, CmpByKeyLength> name_score_map;
2⃣️对有序map中的value排序
把map中的元素放到序列容器(如vector)中,再用sort进行排序
bool cmp(const pair<string, int>& a, const pair<string, int>& b) {
return a.second < b.second;
}
// 将map中的内容转存到vector中
vector<pair<string, int>> vec(name_score_map.begin(), name_score_map.end());
//对线性的vector进行排序
sort(vec.begin(), vec.end(), cmp);
for (int i = 0; i < vec.size(); ++i)
cout << vec[i].first << endl;
例题,找出一串数字中出现次数最多的那个数
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <math.h>
#include <iomanip>
#include <map>
using namespace std;
bool cmp(const pair<long long, int>& a, const pair<long long, int>& b) {
return a.second < b.second;
}
int main(){
int n;
cin >> n;
map<long long, int> box;
long long ai;
for(int i=0; i<n; i++){
cin >> ai;
if(box.find(ai) != box.end())
box[ai] += 1;
else
box[ai] = 1;
}
// 将map中的内容转存到vector中
vector<pair<long long, int>> vec(box.begin(), box.end());
//对线性的vector进行排序
sort(vec.begin(), vec.end(), cmp);
cout << vec.rbegin()->first << " " << vec.rbegin()->second << endl;
}
vec.rbegin()代表最后一个元素,end()代表最后元素之后的,为空