我有以下一段代码,它接收一些单词,将它们存储到一个 vector 中,对它们进行排序,然后计算每个单词出现的次数并将其输出:
typedef vector<double>::size_type vec_sz;
vector<string> words;
string c;
cout << "Enter some words!" << endl << endl;
while (cin >> c) {
words.push_back(c);
}
vec_sz size = words.size();
sort(words.begin(), words.end());
string current_word = words[0];
int count = 1;
for (int i = 1; i < size; i++) {
if (words[i] == current_word) {
count++;
}
else {
cout << "The word " + current_word + " appears " << count << " times." << endl;
current_word = words[i];
count = 1;
}
}
我输入一些词:
word
word
lol
hello
lol
word
hello
^Z
然后我得到以下输出:
The word hello appears 2 times.
The word lol appears 2 times.
但它永远不会到达最终的单词集。我将循环更改为只打印出 vector 中的每个元素,它确实打印出了所有元素。但出于某种原因,这个循环不想到达最终的单词集。出了什么问题?
最佳答案
这里是最后一句话:
else {
// Previous word printed
cout << "The word " + current_word + " appears " << count << " times." << endl;
// current_word set to last word
current_word = words[i];
count = 1;
}
然后循环退出。因此,您需要在循环外添加最后一行来打印最后一个单词及其计数。
关于c++ - vector 循环未到达所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11268529/