关于map遍历的几种方式

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 
#include 
#include 
#include 
#include 
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做面试题的时候发现报错,赶紧全部换成第二种写法。


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部