获取意外的大整数
Getting unexpected large integer
我正在举一个例子来计算一个单词在给定输入中出现的次数。这是我的代码:
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;
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- 长整数的意外模仿行为
- C++意外的整数提升
- 函数中查找整数部首的意外行为/错误
- 将 std::sort 与指向整数变量的指针一起使用会产生意外的输出
- 初始化和显示整数向量时出现意外结果
- <Functional>:<long>整数上的加号()给出意外的结果
- 使用字符串流从 c++ 中的字符串中提取整数时意外重复
- 浮点数据意外地成功将 istream 输入为整数
- 获取意外的大整数
- 构造函数中对整数数组的memcpy()操作在C++中给出了意外的输出
- 使用%c扫描整数,使用%d扫描字符:意外结果
- 常量整数意外更改C++
- 64位整数方程的意外结果
- 整数乘法和除法之间意外的明显性能差异