C++ multimap equal_range() 函数使用示例及常见错误分析
#include
using namespace std;
int main() { 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'; auto pr = mp.equal_range(key); auto it = pr.first; for (it = pr.first; it != pr.second; it++) { cout << it->first << ' ' << it->second << endl; } return 0; }
代码中存在以下错误:
- 缺少头文件
iostream和map。 - 缺少头文件
string。 - 使用了注释符号
//,但没有注释掉相关代码。 - 使用了
cout和endl,但没有包含相应的头文件iostream。 - 使用了
make_pair函数,但没有包含相应的头文件utility。 - 使用了
auto关键字,但没有包含相应的头文件iterator。
修复后的代码:
#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;
int main()
{
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';
auto pr = mp.equal_range(key);
auto it = pr.first;
for (it = pr.first; it != pr.second; it++) {
cout << it->first << ' ' << it->second << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/quAU 著作权归作者所有。请勿转载和采集!