Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Reverse a mapping of map<string, int> to vector<vector<string> >




Building on my prior question, I have a mapping of words & their counts stored in a map<string, int>. I want to reverse that, so that all the words with the same count are group together. My solution was to use a vector<vector<string> >. The index of the first vector being the count & the 2nd vector being the collection for words.

After reading the answers to the prior question, here what I've been trying to make work:

  vector<vector<string> > sorted_words;
    for (map<string, int>::const_iterator it = counters.begin();
       it != counters.end(); ++it) {
    cout << "word:" << it->first
         << " count:" << it-> second
         << " vector size: " << sorted_words.size()
         << endl;

    if (sorted_words.size() - 1 > it->second && 
        sorted_words[ it->second ].size() > 0) {
      cout << "Adding " << it->first << endl;
      sorted_words[ it->second ].push_back(it->first);
    } else {
      cout << "Creating " << it->first << endl;
      vector<string> v;
      sorted_words.resize( it->second + 1 );
      sorted_words[it->second] = v;

This results in a segfault on the very first pass of the loop, at the if statement.

What I'm trying to do is see if the outer vector is sized such that my current value is inbounds & if so, if I've already created a nested vector. (I need to do this, because the map can come back in any order. E.g., the very first element could be <"foo", 3>.)

If I'm going about it in a fundamentally non-C++ way, feel free to point that as well.

like image 218
They Call Me Bruce Avatar asked Mar 25 '23 04:03

They Call Me Bruce

1 Answers

Quick wild ass guess: sorted_words.size() is some unsigned type (namely size_t) so sorted_words.size() - 1 is unsigned even when it should be -1 (initially) thus you always pass the first condition and the second half of the if condition evaluates and crashes.

like image 99
Ben Jackson Avatar answered Mar 26 '23 17:03

Ben Jackson