i was experimenting with algorithm and lambdas when i came across this weird bug:
#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;
}
i am aware that the vector vec, contains the values 1 - 10, when i check for odd numbers using the count_if algorithm, it returns the expected number which is 5(1,3,5,7,9) but when i check for even numbers i get the result = 15, which is weird. what's going on?
Here:
vector<int> vec(10);
You first create a vector of size 10 with value-initialized elements, so all having value 0 (this is probably the part you were misunderstanding).
Then, here:
for (int i = 1 ; i <= 10 ; ++i)
{
vec.push_back(i);
}
You add further 10 elements ranging from 1 to 10, which means you are adding exaclty 5 even elements. Therefore, the number of even elements is 15, and the output is correct.
Also notice, that your predicate is indeed selecting the even numbers, not the odd numbers (which is what seems to be your intention):
[](int v){return v%2 == 0;}
// ^^^^
// This makes your predicate select EVEN numbers!
You should then rewrite it as (for instance):
[](int v){return v%2 != 0;}
// ^^^^
// This makes your predicat select ODD numbers
As a side note, in C++11 you could use the new std::iota algorithm do what I guess you originally meant to do:
#include <algorithm> // <== NECESSARY FOR std::iota
// ...
iota(begin(vec), end(vec), 1);
Which is the same as (in C++03):
for (int i = 1 ; i <= 10 ; ++i)
{
vec[i] = i;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With