我正在制作一个程序,以基本上显示有关用户输入的单词的统计信息。到目前为止,该程序的其余部分都还不错,但是我很难为类型vector
的{{1}}添加单词。
我环顾四周,找到了几个答案,我以为可以解决我的问题,但是我遇到了一个非常奇怪的编译器错误,或者它根本不起作用。我尝试将WordCount
和emplace_back
用于我认为正确的呼叫。本质上,我的问题代码如下:
push_back
为此,我必须使用向量,并且不能按照指示使用指针(如我所见)或#include <iostream>
#include <string>
#include <vector>
using namespace std; //for simplicity here
struct WordCount {
string word;
int count;
//I have tried using this too:
WordCount(string _word, int _count) : word{_word}, count{_count} {}
};
//...//
void wordToVector(/**...**/,string addStr, vector<WordCount>& wordStats){
/**... code that I've tested to work; basically determined if the
word was already said as I need to have unique words only...**/
wordStats.push_back(WordCount(addStr, 1));
/** also tried: (some had "#include <istream>" when using emplace_back
but that didn't seem to make a difference for me in any case)
wordStats.emplace_back(WordCount(addStr, 1));
wordStats.emplace_back({addStr, 1});
wordStats.push_back(addStr, 1)
wordStats.push_back(addStr).word; (and wordStats.push_back(1).count;)
**/
}
int main() {
vector<WordCount> wordStats(1); //"1" to initialize the size
wordStats.at(0).word = "";
wordStats.at(0).count = 0;
/**There's already a part to change the first values to what they should
be, and it worked last I tested it. Below is a part was for my
personal use to see if anything came out... if it worked**/
for (int i = 0; i < 3; i++) {
cout << wordStats.at(i).word << endl;
cout << wordStats.at(i).count << endl;
}
return 0;
}
。如果我输入“ Oh happy day!”,它应该可以打印(固定后,使用当前的cout语句):
OH
1
快乐
1
DAY
1
(有一个较早的部分将每个字母都大写,我测试过可以使用)。 这是我在这里的第一篇文章,因为我迷路了。如果我提供过多或不足,请让我知道。 **编辑格式
答案 0 :(得分:2)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct WordCount {
string word;
int count;
};
void wordToVector(string addStr, vector<WordCount>& wordStats){
for (int i = 0; i < wordStats.size(); i++) {
if (wordStats[i].word == addStr) {
wordStats[i].count = wordStats[i].count + 1;
return;
}
}
struct WordCount wc;
wc.word = addStr;
wc.count = 1;
wordStats.push_back(wc);
}
int main() {
vector<WordCount> wordStats;
wordToVector("hehe", wordStats);
wordToVector("hehe", wordStats);
wordToVector("haha", wordStats);
for (int i = 0; i < wordStats.size(); i++) {
cout << wordStats.at(i).word << endl;
cout << wordStats.at(i).count << endl;
}
return 0;
}
使用此代码,我得到输出:
hehe
2
haha
1
还有什么需要补充的吗?
如果要用空格分割输入并检查输入中每个单词的出现,则较长的文本检查每个单词可能效率很低(我想这是线性的,M * N复杂度)如果允许的话,我建议您使用以单词为键,值作为出现次数的地图-或类似的方式。