I have 2 different pieces of code but resulting in the same thing.
The first one is using the iterative method:
const std::vector<int> vec {1,8,2,96,47,23};
int sum {};
for(const auto& i: vec)
sum += (i % 2) ? 1 : 0;
And the second piece of code is the following:
const std::vector<int> vec {1,8,2,96,47,23};
const int sum = std::count_if(vec.begin(), vec.end(), [](const int& i){return i % 2 != 0;});
My question is why when using the -O1
optimization the iterative method wins and when using -O3
or -Ofast
the algorithmic method wins.
I expected that the algorithmic method will win in either cases.
Can someone explain?