【发布时间】: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;
}
【问题讨论】: