0

我正在按照一个示例来计算一个单词在给定输入中出现的次数。这是我的代码:

string word, the_word;
int count(0);
vector<string> sentence;
auto it = sentence.begin();
cout << "Enter some words. Ctrl+z to end." << endl;
while (cin >> word)
    sentence.push_back(word);

the_word = *sentence.begin();
cout << the_word << endl;
while(it != sentence.end()) {
    if(*sentence.begin() == the_word)
        ++count;
    ++it;
}
cout << count << endl;

我给出的输入是“现在怎么样现在棕色奶牛”。我希望count是 3,但我得到的是 200 万的整数。我错过了什么?

4

1 回答 1

2

无效的迭代器

auto it = sentence.begin()

it在插入值之前进行分配。在输入循环之后移动这一行。

+-- auto it = sentence.begin();
|   ^^^^^^^^^^^^^^^^^^^^^^^^^^^
|    
|   while (cin >> word)
|       sentence.push_back(word);
|
+--> // Move it here.


    if(*sentence.begin() == the_word)
        ^^^^^^^^^^^^^^^^
        // Change to *it

您也可以std::count改用:

cout << "Enter some words. Ctrl+z to end." << endl;

vector<string> v((istream_iterator<string>(cin)),istream_iterator<string>());

int c = v.size()? count(v.begin(), v.end(), v.front()) : 0;
于 2013-09-08T21:09:28.977 回答