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?
I guess it's because you are dereferencing
j
when it can point toend
:And here's the change to fix it: