1、迭代器遍历
老方法,缺点是有点耗时。
map<int, int> mp;
map<int, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++) {
cout << it->first << ' ' << it->second << endl;
}
2、auto的两种遍历方式
接下里两种在一个例子里体现,一串带有英文的字符串,找出出现次数最多的字符并输出:
#include <iostream>
#include <cstring>
#include <map>
#include <utility>
#include <string>
using namespace std;
//英文字符串出现最多的字符并打印
string s;
int main() {
getline(cin, s);
map<char, int> mp;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
// 判断是否合法
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
mp[c]++;
}
else {
cout << "error" << endl;
return -1;
}
}
int maxNum = 0;
for (auto &[k, v] : mp) { // 这种遍历方式在C17中才可以使用
maxNum = max(maxNum, v);
}
for (auto k : mp) {
if (maxNum == k.second) cout << k.first << ' ';
}
cout << endl;
return 0;
}
以上两种对mp的遍历方式,第一种写法在C17以后才可以使用,今天用VS2019做面试题的时候发现报错,赶紧全部换成第二种写法。