2012-02-29 31 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 2012-02-29 04:06:03

+0

[在輸出和銷燬之前按值排序std :: map](http://stackoverflow.com/questions/1367429/sorting-a-stdmap-by-value-before-output-destroy) – 2012-02-29 04:06:53

回答

2

創建一個向量std::pair<int,string>,然後使用地圖內容填充它,然後進行排序。

Boost有一些創建可以通過鍵或值遍歷的映射的方法,但我認爲這在這種情況下是過度的。