所以有点背景。我应该制作一个程序,通过一个段落,逐行,并挑选出每行最常用的单词。我已经有效地编写了一个代码,用于在一个向量中存储一行的内容,现在我需要将frequncey分配给这些单词。我正在使用地图,但它并没有给我预期的结果。我是C ++数据结构的新手,所以一些建议将不胜感激。
map<string,int> freq; //map for getting frequency on line
for(int i=0;i<currLine.size();i++){ //loops through the words on the line
string currName=currLine.at(i); //current word
//cout<<currName<<endl;
if(freq.find(currName)!=freq.end()){ //if already present
int update=freq.at(currName)+1; //this value takes the value and adds one
freq.insert(pair<string,int>(currName,update)); //insert back into the string with updated value
//cout<<freq.at(currName);
}
else{
freq.insert(pair<string,int>(currName,0)); //if not present, then insert with value 0
}
}
例如:
- 和你不一样,我对gnu感到不快。 别介意我和我一起吃饭? 乔治奥威尔在1984年错了。 你的猫代码可以吗?如果没有,你的狗代码可以吗? 我喜欢玩后果游戏。建议你也玩它。 足球是美国以外最受欢迎的运动。
会回归:“不像我,乔治可以踢足球”
int main()
{
string line;
vector<string> result;
while(getline(cin,line)){ //on each line
vector<string> currLine; //stores words on line
string curr=""; //temp string for grasping words
for(int i=0;i<line.length();i++){ //loops through line
if(isalpha(line.at(i))){ //if it is a letter, add it to the temp string
curr+=tolower(line.at(i));
}
else if(line.at(i)=='\''){
//do nothing
}
else{ //if not, then add the previous word to vector and reset temp string
currLine.push_back(curr);
curr="";
}
}
vector< pair<string, int> > freq(10);
//freq.push_back(make_pair("asd",2));
for(int i=0;i<currLine.size();i++){
string curr1=currLine.at(i);
cout<<curr1<<" ";
for(int j=0;j<freq.size();j++){
if(freq.at(j).first==curr1){ //if present in the list
//cout<<"Duplicate found";
freq.at(j).second++; //increment second value
}
else{
//cout<<"Pair Made";
freq.push_back(make_pair(curr1,1));
break;
}
}
}
int max=0;
string currMost;
for(int i =0;i<freq.size();i++){
if(freq.at(i).second>max){
max=freq.at(i).second;;
currMost=freq.at(i).first;
}
}
//cout<<currMost;
cout<<endl;
// result.push_back(currMost);
}
for(int i=0;i<result.size();i++){
cout<<result.at(i);
}
}
答案 0 :(得分:2)
我首先将句子分成单词,然后将它们存储到地图中。地图插入最简单,最明显的方法是使用map[key] = value
表示法。我首先使用count()
函数检查该值是否已存在并插入该值,否则我将增加已存在的键的值。
map <string, int> word_frequency;
string word="";
for (int i=0; i<=current_line.length();i++){
if (current_line[i]!=' ' && i< current_line.length()){
word = word + current_line[i];
}
else if(word_frequency.count(word) == 0){
word_frequency[word] = 0;
word = "";
}
else{
word_frequency[word]++;
word = "";
}
}