0

I am currently working on a project where I have to read a text file word by word and insert each word into a STL map, where the key is the word and the value is the number of times the word has appeared. This section of the problem makes sense to me (I populate a vector with each word and then iterate through the vector and insert each word into the map and depending if its already in the map I insert it).

The next part of the problem then asks me to print out a histogram in order, sorted by the word count. If you take a look at my code below I am using sMap.begin() and sMap.end() (I know that sMap.rbegin and rend will give the reverse of the list). The map is currently sorting my the key values. Is there a simple way to force my map to sort by the values or would I have to do some type of map copying?

        int main(){
          using namespace std;
          char* filename = "dracula.txt";
          ifstream in(filename);
          vector<string> contents;
          string tempWord;
          map<string, int> sMap;

          while(in>>tempWord)
            contents.push_back(tempWord);
          // now we have a vector with every word
          int i =0;
          for(i;i<contents.size();i++){
            // insert into the STL Map
            map<string,int>::iterator it = sMap.find(contents[i]);
            if(it==sMap.end()){
              // we just need to insert the element with an occurence of 1
              sMap.insert(map<string,int>::value_type(contents[i],1));  
            }else{
              int temp = it->second;
              sMap.erase (it);
              sMap.insert(map<string,int>::value_type(contents[i],temp+1));
            }
          }
          // now we have a filled map with all the words in the file
          // we just need to sort the map based on the occurences
          map<string,int>::iterator rit;
          for(rit=sMap.begin(); rit != sMap.end();rit++){
            cout << rit->first << ": ";
            for(int q = rit->second; q>0; q--){
              cout << "|";
            }
            cout << endl;
          }
    return EXIT_SUCCESS;
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
Dan Bradbury
  • 2,071
  • 2
  • 21
  • 27
  • Please check [this answer](http://stackoverflow.com/questions/2699060/stl-map-sort-by-value). – Sergey Kalinichenko Feb 29 '12 at 04:06
  • possible duplicate of [Sorting a std::map by value before output & destroy](http://stackoverflow.com/questions/1367429/sorting-a-stdmap-by-value-before-output-destroy) – Brian Roach Feb 29 '12 at 04:06

1 Answers1

2

Create a vector of std::pair<int,string> and populate it with the contents of the map, then sort.

Boost has some ways of creating a map that can be traversed by key or value, but I think that's overkill in this case.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622