获得意外的大整数

时间:2013-09-08 21:06:03

标签: c++ iterator

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

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,但我会得到2百万的整数。我错过了什么?

1 个答案:

答案 0 :(得分: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;