2012-02-29 9 views
0

私は現在、単語ごとにテキストファイルを読み込んで各単語をSTLマップに挿入しなければならないプロジェクトに取り組んでいます。ここで、キーは単語であり、値は数値です単語の出現回数。問題のこのセクションは私にとって意味があります(各単語にベクトルを入力し、ベクトルを繰り返して、各単語をマップに挿入し、マップに既に挿入されているかどうかによって異なります)。キーではなく値でマップを並べ替える

次に、問題の次の部分では、ワードカウントでソートされた順にヒストグラムを印刷するように求められます。私のコードを見てみると、私はsMap.begin()とsMap.end()を使っています(sMap.rbeginとrendがリストの逆を与えることはわかっています)。マップは現在、私のキー値をソートしています。値でソートするようにマップを強制する簡単な方法はありますか、ある種のマップコピーをする必要がありますか?

 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; 
} 
+0

[この回答](http://stackoverflow.com/questions/2699060/stl-map-sort-by-value)を確認してください。 – dasblinkenlight

+0

[出力前の値でstd :: mapを並べ替えると破棄する](http://stackoverflow.com/questions/1367429/sorting-a-stdmap-by-value-before-output-destroy) –

答えて

2

その後、ソート、std::pair<int,string>のベクトルを作成し、マップの内容を移入。

ブーストには、キーや値によって横断できるマップを作成する方法がいくつかありますが、この場合は残念です。

関連する問題