如何获取multimap内key为i的所有value

错误示范:

//测试如何获取multimap内key为i的所有value
/* 
* multimap容器的find()函数返回一个迭代器,此迭代器引用 multimap 当中具有与指定键等效的键的元素的第一个位置。
* 而且mutimap容器中的数据是根据key值自动排序了的。
*/
void getKey(multimap<int, string>& m1, int i) {
	cout << "map容器内Key为"<<i<<"的数据有:" << endl;

	multimap<int, string>::const_iterator it2 = m1.find(i);
	for (multimap<int, string>::const_iterator it = it2; it->first == i; it++) {
		cout << it->first << " " << it->second << endl;
	}
}

 问题在于,若获取的是key值最大的数据时,其最后一个数据的地址就是我们容器的最后一个地址。

获取完最后一个元素地址,it++后,此时,it=m.end();即此时it相当于空指针,因此it->first这里无法访问。

 

正确操作

void getKey(multimap<int, string>& m1, int i) {
	cout << "map容器内Key为"<<i<<"的数据有:" << endl;

	/*multimap<int, string>::const_iterator it2 = m1.find(i);
	for (multimap<int, string>::const_iterator it = it2; it->first == i; it++) {
		cout << it->first << " " << it->second << endl;
	}*/

	int count = m1.count(i);
	multimap<int, string>::const_iterator it = m1.find(i);

	for (int i = 0; i < count; i++) {
		cout << it->first << " " << it->second << endl;
		it++;
	}
}

 

posted @   晚生小白  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示