std::all_of, std::any_of, std::none_of
cppreference.com
<algorithm> 에 정의되어 있음.
|
||
template< class InputIt, class UnaryPredicate > bool all_of( InputIt first, InputIt last, UnaryPredicate p ); |
(1) | (since C++11) |
template< class InputIt, class UnaryPredicate > bool any_of( InputIt first, InputIt last, UnaryPredicate p ); |
(2) | (since C++11) |
template< class InputIt, class UnaryPredicate > bool none_of( InputIt first, InputIt last, UnaryPredicate p ); |
(3) | (since C++11) |
1) 단항 의문술어
p
가 지정된 범위 [first, last)
안의 모든 요소들에 대해서 true 를 반환하는지 검사한다.2) 단항 의문술어
p
가 지정된 범위 [first, last)
안의 요소들에 대해서 하나라도 true 를 반환하는지 검사한다.3) 단항 의문술어
p
가 지정된 범위 [first, last)
안의 요소들에 대해서 true 를 반환하는 요소가 없는지 검사한다.목차 |
[편집] 파라미터
first, last | - | 검사할 요소들의 범위. |
p | - | 단항 의문술어 . 의문술어 함수의 ��자형식(signature)은 다음과 같아야 한다 : bool pred(const Type &a); 인자형식(signature)이 const &일 필요는 없다, 하지만 넘겨받은 객체를 수정해서는 안된다. |
형식의 필요조건 | ||
-InputIt 는 다음 조건을 만족해야 한다 : InputIterator .
| ||
-UnaryPredicate 는 다음 조건을 만족해야 한다 : Predicate .
|
[편집] 반환값
1) 단항 의문술어가 지정 범위안의 모든 요소에 대해서 true 를 반환하면 true, 그렇지 않으면 false. 범위가 비어있다면 true 를 반환한다.
2) 단항 의문술어가 지정 범위안의 한 요소라도 true 를 반환하면 true, 그렇지 않으면 false. 범위가 비어있다면 false 를 반환한다.
3) 단항 의문술어가 지정 범위안의 모든 요소에 대해서 true 를 반환하는 것이 없다면 true, 그렇지 않으면 false. 범위가 비어있다면 true 를 반환한다.
[편집] 복잡도
의문술어 대비 최고 last
- first
만큼 적용된다.
[편집] 가능한 구현
First version |
---|
template< class InputIt, class UnaryPredicate > bool all_of(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if_not(first, last, p) == last; } |
Second version |
template< class InputIt, class UnaryPredicate > bool any_of(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if(first, last, p) != last; } |
Third version |
template< class InputIt, class UnaryPredicate > bool none_of(InputIt first, InputIt last, UnaryPredicate p) { return std::find_if(first, last, p) == last; } |
[편집] 예제
코드 실행
#include <vector> #include <numeric> #include <algorithm> #include <iterator> #include <iostream> #include <functional> 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"; } if (std::none_of(v.cbegin(), v.cend(), std::bind(std::modulus<int>(), std::placeholders::_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"; } }
Output:
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