c++ - "Expression: vector iterator not deferencable" run-time error -


the following code inputs words , counts how many times each word appeared in input. program prints each word , corresponding frequency in order lowest 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 = counters.begin();     (it; != counters.end(); ++it)     {         freq[it->second].push_back(it->first);     }      (map<int, vector<string> >::const_iterator = freq.begin();         != 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 , runs, whenever enter words need , enter eof following run-time error appears

expression: vector iterator not dereferencable

and following error appears

standard c++ libraries out of range && 0

how resolve it?

i guess it's because dereferencing j when can point end:

    cout << i->first << '\t' << *j;                                 ^----- here 

and here's change fix it:

    if (j != i->second.end()) {         cout << i->first << '\t' << *j;     } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -