std::ranges::is_partitioned
| 在标头 <algorithm>
|
||
| 调用签名 |
||
template< std::input_iterator I, std::sentinel_for<I> S,
class Proj = std::identity,
std::indirect_unary_predicate<std::projected<I, Proj>> Pred >
constexpr bool
is_partitioned( I first, S last, Pred pred, Proj proj = {} );
|
(1) | (自 C++20 起) |
template< ranges::input_range R, class Proj = std::identity,
std::indirect_unary_predicate<
std::projected<ranges::iterator_t<R>, Proj>> Pred >
constexpr bool
is_partitioned( R&& r, Pred pred, Proj proj = {} );
|
(2) | (自 C++20 起) |
true 如果范围 [first, last) 中所有满足谓词 pred 在投影后的元素出现在所有不满足的元素之前。也返回 true 如果 [first, last) 为空。r 作为源范围,如同以 ranges::begin(r) 作为 first 并以 ranges::end(r) 作为 last。本页描述的函数式实体是 算法函数对象(非正式称为 niebloid),即:
参数
| first, last | - | 定义待检验元素范围的 区间 的迭代器-哨位对 |
| r | - | 待检验的元素范围 |
| pred | - | 应用于投影元素的谓词 |
| proj | - | 应用于元素的投影 |
返回值
若范围
[
first
,
last
)
为空或被
pred
划分则返回
true
,否则返回
false
。
复杂度
最多 ranges:: distance ( first, last ) 次对 pred 和 proj 的应用。
可能的实现
struct is_partitioned_fn { template<std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_unary_predicate<std::projected<I, Proj>> Pred> constexpr bool operator()(I first, S last, Pred pred, Proj proj = {}) const { for (; first != last; ++first) if (!std::invoke(pred, std::invoke(proj, *first))) break; for (; first != last; ++first) if (std::invoke(pred, std::invoke(proj, *first))) return false; return true; } template<ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred> constexpr bool operator()(R&& r, Pred pred, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj)); } }; inline constexpr auto is_partitioned = is_partitioned_fn(); |
示例
#include <algorithm> #include <array> #include <iostream> #include <numeric> #include <utility> int main() { std::array<int, 9> v; auto print = [&v](bool o) { for (int x : v) std::cout << x << ' '; std::cout << (o ? "=> " : "=> not ") << "partitioned\n"; }; auto is_even = [](int i) { return i % 2 == 0; }; std::iota(v.begin(), v.end(), 1); // 或 std::ranges::iota(v, 1); print(std::ranges::is_partitioned(v, is_even)); std::ranges::partition(v, is_even); print(std::ranges::is_partitioned(std::as_const(v), is_even)); std::ranges::reverse(v); print(std::ranges::is_partitioned(v.cbegin(), v.cend(), is_even)); print(std::ranges::is_partitioned(v.crbegin(), v.crend(), is_even)); }
输出:
1 2 3 4 5 6 7 8 9 => not partitioned 2 4 6 8 5 3 7 1 9 => partitioned 9 1 7 3 5 8 6 4 2 => not partitioned 9 1 7 3 5 8 6 4 2 => partitioned
参见
|
(C++20)
|
将元素范围划分为两组
(算法函数对象) |
|
(C++20)
|
定位已划分范围的分割点
(算法函数对象) |
|
(C++11)
|
判断范围是否按给定谓词划分完成
(函数模板) |