Find the only one element in C++ containers

Viewed 90

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?

1 Answers

You can call find_if twice, at the 2nd time call it from the iterator found at the 1st time if found.

int test(const array<int, 8> &arr) {
  auto isEven = [](int i){return i % 2 == 0;};
  auto it = find_if(arr.begin(), arr.end(), isEven);
  if (it == arr.end()) return 0;  // not found, the number of even in the array is 0
  auto it2 = find_if(it + 1, arr.end(), isEven);
  if (it2 != arr.end()) return 0; // found, the number of even in the array is more than 1
  return *it;
}
Related