std::none_of() 算法
- 自 C++20 起
- 自 C++17 起
- 自 C++11 起
// (1)
template< class InputIt, class UnaryPredicate >
constexpr bool none_of( InputIt first, InputIt last, UnaryPredicate p );
// (2)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
bool none_of( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
UnaryPredicate p );
// (1)
template< class InputIt, class UnaryPredicate >
bool none_of( InputIt first, InputIt last, UnaryPredicate p );
// (2)
template< class ExecutionPolicy, class ForwardIt, class UnaryPredicate >
bool none_of( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
UnaryPredicate p );
// (1)
template< class InputIt, class UnaryPredicate >
bool none_of( InputIt first, InputIt last, UnaryPredicate p );
检查某个谓词是否对范围内的所有元素都不成立。
-
(1) 检查一元谓词
p
是否对范围 [first
;last
) 中的每个元素都返回 false。 -
(2) 与 (1) 相同,但根据
policy
执行。重载决议这些重载只有在
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>
为true
时才参与重载决议。 (直到 C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
为true
时才参与重载决议。 (自 C++20 起)
参数
first second | 要检查的元素范围。 |
policy | 要使用的执行策略。有关详细信息,请参阅执行策略。 |
p | 一元谓词。 对于类型为(可能是 const) |
类型要求
InputIt | LegacyInputIterator |
ForwardIt | LegacyForwardIterator |
UnaryPredicate | Predicate |
返回值
如果一元谓词对范围内的任何元素都不返回 true
,则为 true
,否则为 false
。
如果范围为空,则返回 true
。
复杂度
- (1) 最多
last - first
次谓词应用。 - (2) O(last - first) 次谓词应用。
异常
带有模板参数 ExecutionPolicy
的重载报告错误如下
- 如果作为算法一部分调用的函数执行抛出异常,并且
ExecutionPolicy
是标准策略之一,则调用std::terminate
。对于其他任何ExecutionPolicy
,行为是实现定义的. - 如果算法未能分配内存,则抛出
std::bad_alloc
。
可能的实现
none_of (1)
template<class InputIt, class UnaryPredicate>
constexpr bool none_of(InputIt first, InputIt last, UnaryPredicate p)
{
return std::find_if(first, last, p) == last;
}
示例
#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::none_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<>(),
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::none_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