algorithm_all_any_none_of
algorithm_all_any_none_of (모든/하나라도/아무것도 조건 검사)
std::all_of, std::any_of, std::none_of는 범위의 요소들이 단항 술어 조건을 얼마나 만족하는지 판단하는 알고리즘이에요. 전부 만족하는지, 하나라도 만족하는지, 아무것도 만족하지 않는지를 각각 검사해요.
출처: cppreference
본문
세 함수 모두 <algorithm> 헤더에 정의되어 있어요. 각각 범위 [first, last)에 대해 단항 술어 p를 검사해요.
template< class InputIt, class UnaryPred >
bool all_of( InputIt first, InputIt last, UnaryPred p );
template< class InputIt, class UnaryPred >
bool any_of( InputIt first, InputIt last, UnaryPred p );
template< class InputIt, class UnaryPred >
bool none_of( InputIt first, InputIt last, UnaryPred p );
all_of— 범위의 모든 요소에 대해p가 참을 반환하는지 검사해요.any_of— 범위의 적어도 하나의 요소에 대해p가 참을 반환하는지 검사해요.none_of— 범위의 어떤 요소에 대해서도p가 참을 반환하지 않는지 검사해요.
병렬 실행 정책을 받는 오버로드도 있어요.
복잡도 (Complexity)
std::distance(first, last)번 이하의 p 적용이 필요해요.
예제 (Example)
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main()
{
std::vector<int> v(10, 2);
std::partial_sum(v.cbegin(), v.cend(), v.begin());
std::cout << "Among the numbers: ";
std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
if (std::all_of(v.cbegin(), v.cend(), [](int i) { return i % 2 == 0; }))
std::cout << "All numbers are even\n";
using namespace std::placeholders;
if (std::none_of(v.cbegin(), v.cend(), std::bind(std::modulus<>(), _1, 2)))
std::cout << "None of them are odd\n";
struct DivisibleBy
{
const int d;
DivisibleBy(int n) : d(n) {}
bool operator()(int n) const { return n % d == 0; }
};
if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7)))
std::cout << "At least one number is divisible by 7\n";
}
출력:
Among the numbers: 2 4 6 8 10 12 14 16 18 20
All numbers are even
None of them are odd
At least one number is divisible by 7
가능한 구현 (Possible implementation)
template<class InputIt, class UnaryPred>
constexpr bool all_of(InputIt first, InputIt last, UnaryPred p)
{
return std::find_if_not(first, last, p) == last;
}
template<class InputIt, class UnaryPred>
constexpr bool any_of(InputIt first, InputIt last, UnaryPred p)
{
return std::find_if(first, last, p) != last;
}
template<class InputIt, class UnaryPred>
constexpr bool none_of(InputIt first, InputIt last, UnaryPred p)
{
return std::find_if(first, last, p) == last;
}