count_if()的算术错误

Arithmetic error with count_if()

本文关键字:错误 if count      更新时间:2023-10-16

当我遇到这个奇怪的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;
}