以下代码输入单词并计算每个单词在输入中出现的次数。然后程序按照从最低到最高的顺序打印每个单词和相应的频率。
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s;
map<string, int> counters;
map<int, vector<string> > freq;
while (cin >> s)
++counters[s];
map<string, int>::const_iterator it = counters.begin();
for (it; it != counters.end(); ++it)
{
freq[it->second].push_back(it->first);
}
for (map<int, vector<string> >::const_iterator i = freq.begin();
i != freq.end(); ++i)
{
vector<string>::const_iterator j = i->second.begin();
cout << i->first << '\t' << *j;
while (j != i->second.end())
{
++j;
cout << ", " << *j;
}
cout << endl;
}
return 0;
}
程序编译并运行,但只要我输入所需的所有单词并输入EOF,就会出现以下运行时错误
Expression:vector iterator not dereferencable
然后还会出现以下错误
标准C ++库超出范围&amp;&amp; 0
如何解决?
答案 0 :(得分:1)
我想是的,因为当它可以指向j
时你正在解除引用end
:
cout << i->first << '\t' << *j;
^----- HERE
以下是修改它的变化:
if (j != i->second.end()) {
cout << i->first << '\t' << *j;
}
答案 1 :(得分:0)
知道了。
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s;
map<string, int> counters;
map<int, vector<string> > freq;
while (cin >> s)
++counters[s];
map<string, int>::const_iterator it = counters.begin();
for (it; it != counters.end(); ++it)
{
freq[it->second].push_back(it->first);
}
for (map<int, vector<string> >::const_iterator i = freq.begin();
i != freq.end(); ++i)
{
vector<string>::const_iterator j = i->second.begin();
cout << i->first << '\t';
for (j; j != i->second.end(); ++j)
cout << *j << " ";
cout << endl;
}
return 0;
}
仍然不知道为什么&#34;而#34; loo [没有工作。