【问题标题】:Sorting a map by values rather than keys按值而不是键对地图进行排序
【发布时间】:2012-02-29 04:01:25
【问题描述】:

我目前正在做一个项目,我必须逐字读取文本文件并将每个单词插入到 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;
}

【问题讨论】:

标签: c++ map


【解决方案1】:

创建一个std::pair&lt;int,string&gt; 的向量并用地图的内容填充它,然后排序。

Boost 有一些方法可以创建可以通过键或值遍历的映射,但我认为在这种情况下这有点过头了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多