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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值