这个程序在映射中存储对,计算一个词出现的次数。目标是让数据按出现次数排序并以值/字符串形式输出。显然法线贴图是按字符串键排序的,所以我不得不颠倒过来。
为此,我用文字阅读,并在 map 中适本地增加它们的值。然后我创建一个 multimap 并将对从 map 复制到 multimap ,但相反。然后我遍历 multimap,输出对。但是,当我尝试输出对时出现运行时错误,我不确定为什么。
代码如下:
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
map<string, int> words;
multimap<int, string> words2;
string s;
while (true) {
cin >> s;
if (s == "0") break;
++words[s];
}
map<string, int>::iterator p;
for (p = words.begin(); p!=words.end(); ++p)
words2.insert(make_pair(p->second, p->first));
multimap<int, string>::iterator p2;
for (p2 = words2.begin(); p2!=words2.end(); ++p2)
cout << p->first << ": " << p->second << '\n';
}
感谢任何帮助。
附言我在不同的地方读到,multimap 可以多次出现一个键(这就是我首先使用它的原因)和/或一个键中的多个值。关于哪个是真的或者两者是否都是真的,一些澄清会很好。
还有 map 的复制算法吗?为了简单起见,我决定只使用 for 循环,编写自定义拷贝可能相当容易,但我只是想知道(将映射复制到其他对容器并复制到输出。)
最佳答案
for (p2 = words2.begin(); p2!=words2.end(); ++p2)
cout << p->first << ": " << p->second << '\n';
输出语句中的 p 不应该是 p2 吗?
关于c++ - 从 map 复制后的 multimap 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354224/