Reputation: 477
The following code inputs words and counts how many times each word appeared in the input. Then the program prints each word and corresponding frequency in the order from lowest to highest.
#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;
}
The program compiles and runs, but whenever I enter all the words I need and enter EOF the following run-time error appears
Expression: vector iterator not dereferencable
and then the following error also appears
Standard C++ libraries out of range && 0
How to resolve it?
Upvotes: 2
Views: 175
Reputation: 1379
I guess it's because you are dereferencing j
when it can point to end
:
cout << i->first << '\t' << *j;
^----- HERE
And here's the change to fix it:
if (j != i->second.end()) {
cout << i->first << '\t' << *j;
}
Upvotes: 1
Reputation: 477
Got it.
#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;
}
Still have no idea why "while" loo[ didn't work.
Upvotes: 0