I want to write a function to find the unique even number in a array.
If the number of even in this array unequal to 1, my function should return 0;
#include <array>
#include <algorithm>
using namespace std;
int test(const array<int, 8> &arr) {
auto isEven = [](int i){return i % 2 == 0;};
if (count_if(arr.begin(), arr.end(), isEven) != 1)
return 0;
auto it = find_if(arr.begin(), arr.end(), isEven);
return *it;
}
I use count_if and end_if to complete the program.
But it is inefficient. The program walk through the array two times in case it finds the only one even.
Does there exists appropriate STL to solve this problem?