在C++容器中查找唯一一个元素



我想写一个函数来查找数组中唯一的偶数
如果此数组中的偶数不等于1,则我的函数应返回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;
}

我使用count_ifend_if来完成程序
但是效率很低。程序遍历数组两次,以防找到唯一一个偶数
是否存在适当的STL来解决此问题?

您可以调用find_if两次,第二次从第一次找到的迭代器中调用(如果找到的话(。

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;
}

最新更新