我正在制作一个程序来基本上显示有关用户输入的单词的统计信息。程序的其余部分到目前为止都很好,但我很难向 vector
添加单词。类型 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;
}
为此我必须使用 vector ,不能使用指针(正如我所看到的建议)或 #include <algorithm>
根据说明。如果我输入“Oh happy day!”,它应该能够打印(修复后,使用当前的 cout 语句):
哦
1
快乐
1
天
1
(有一个前面的部分将每个字母都大写,我测试过它可以工作)。 这是我在这里的第一篇文章,因为我迷路了。如果我提供的太多或不够,请告诉我。 **编辑格式
最佳答案
#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),所以如果你被允许,我建议使用一个 map ,其中单词作为键,值作为出现次数 - 或者以那种方式。
关于c++ - 尝试将元素添加到使用 Struct 分类的 Vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55392672/