如何获取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++;
}
}
浙公网安备 33010602011771号