count_if()的算术错误
Arithmetic error with count_if()
当我遇到这个奇怪的bug时,我正在试验算法和lambdas:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
vector<int> vec(10);
int OddCount;
for (int i = 1 ; i <= 10 ; ++i)
{
vec.push_back(i);
}
OddCount = count_if(vec.begin(),vec.end(),[](int v){return v%2 == 0;});
cout<<OddCount<<endl;
return 0;
}
我知道向量vec,包含值1 - 10,当我使用count_if算法检查奇数时,它返回预期的数字是5(1,3,5,7,9),但当我检查偶数时,我得到的结果= 15,这很奇怪。这是怎么呢
此处:
vector<int> vec(10);
你首先用值初始化的元素创建一个大小为10
的向量,所以所有元素的值都是0
(这可能是你误解的部分)。
,这里:
for (int i = 1 ; i <= 10 ; ++i)
{
vec.push_back(i);
}
再添加 10个元素,范围从1到10,这意味着你添加了5个偶数元素。因此,偶数元素的个数为15,输出正确。
还要注意,您的谓词确实选择了偶数,而不是奇数(这似乎是您的意图):
[](int v){return v%2 == 0;}
// ^^^^
// This makes your predicate select EVEN numbers!
你应该重写为(例如):
[](int v){return v%2 != 0;}
// ^^^^
// This makes your predicat select ODD numbers
作为旁注,在c++ 11中,您可以使用新的std::iota
算法做我猜您最初打算做的事情:
#include <algorithm> // <== NECESSARY FOR std::iota
// ...
iota(begin(vec), end(vec), 1);
与c++ 03中的
相同:for (int i = 1 ; i <= 10 ; ++i)
{
vec[i] = i;
}
相关文章:
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- 错误:无效的预处理指令 #i 的意思是 #if?
- 为什么切换 if else 语句的顺序会导致错误?
- 为什么 if 语句在 Java 中"if(1)"给出错误,但在C++中成立?
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 我如何在一个 if 语句中声明所有数字我尝试通过其他方式声明所有数字,如果一个接一个,但似乎代码有逻辑错误
- 在if constexpr中使用带参数包的概念时,升级到gcc 9后出现编译错误
- 编译器错误"在if语句中分配不兼容的类型"
- C++ if 语句错误
- 否则在新程序中没有以前的 if 错误
- 对'if constexpr'的错误理解
- C++带有 while 语句范围捕获的 if 语句中的错误
- 将子字符串与字符串数组进行比较的 IF 条件会在C++中产生错误
- c++ IF 语句执行,但添加 ELSE 会显示错误
- 在 constexpr-if 条件下比较 constexpr 函数参数会导致错误
- C++ 带有 if 语句的家庭作业编译错误
- 为什么使用 and 运算符比较 if 语句中的 2 个对象会抛出错误,而使用 2 if 语句则不会
- C++ do/while 循环和 if/else: 骰子游戏 -- 第 75 行错误:"Cout"之前的预期"While" -- 如何解决这个问题?
- SDL 应用程序错误:“if”之前应为非限定 id
- 第 48 行和第 62 行 C++错误 if之前的预期非限定 id