获取意外的大整数

Getting unexpected large integer

本文关键字:整数 意外 获取      更新时间:2023-10-16

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

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 万中的整数。我错过了什么?

无效迭代器

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;