C++ multimap 使用详解:插入、查找、遍历和错误修正
#include
#include
using namespace std;
int main() { // map<key_t, value_t> multimap<string, int> mp; //mp["one"] = 1; //error no [] mp.insert(make_pair("one", 20)); mp.insert(make_pair("two", 20)); mp.insert(make_pair("two", 10)); mp.insert(make_pair("two", 30)); mp.insert(make_pair("two", 40)); cout << "count two " << mp.count("two") << endl; string key = "two"; // pair< multimap<string, int>::iterator, multimap<string, int>::iterator > pr = mp.equal_range(key); // auto pr = mp.equal_range(key); auto it = mp.lower_bound(key); auto end = mp.upper_bound(key); for(it; it != end; it++) { cout << it->first << " " << it ->second << endl; } return 0; }
代码中有一些错误:
-
在使用map时,不能直接使用
mp["one"] = 1;来赋值,应该使用mp.insert(make_pair("one", 20));来插入键值对。 -
在使用equal_range函数时,需要注释掉相关代码,因为此处并未使用该函数。
以下是修改后的代码:
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
// map<key_t, value_t>
multimap<string, int> mp;
mp.insert(make_pair("one", 20));
mp.insert(make_pair("two", 20));
mp.insert(make_pair("two", 10));
mp.insert(make_pair("two", 30));
mp.insert(make_pair("two", 40));
cout << "count two " << mp.count("two") << endl;
string key = "two";
// pair< multimap<string, int>::iterator, multimap<string, int>::iterator > pr = mp.equal_range(key);
// auto pr = mp.equal_range(key);
auto it = mp.lower_bound(key);
auto end = mp.upper_bound(key);
for(it; it != end; it++) {
cout << it->first << " " << it ->second << endl;
}
return 0;
}
在这个例子中,我使用了lower_bound和upper_bound函数来找到特定键的范围,然后遍历输出结果。
原文地址: https://www.cveoy.top/t/topic/quAK 著作权归作者所有。请勿转载和采集!