std::ranges::is_partitioned
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::input_iterator I, std::sentinel_for<I> S, class Proj = std::identity, |
(1) | (C++20 起) |
template< ranges::input_range R, class Proj = std::identity, std::indirect_unary_predicate< |
(2) | (C++20 起) |
1) 如果範圍
[
first,
last)
中所有在投影后滿足謂詞 pred 的元素都出現在所有不滿足的元素之前,則返回 true。如果 [
first,
last)
為空,也返回 true。本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first, last | - | 定義要檢查的元素 範圍 的迭代器-哨兵對 |
r | - | 要檢查的元素範圍 |
pred | - | 應用於投影元素的謂詞 |
proj | - | 應用於元素的投影 |
[編輯] 返回值
如果範圍 [
first,
last)
為空或被 pred 分割,則返回 true,否則返回 false。
[編輯] 複雜度
最多對 pred 和 proj 應用 ranges::distance(first, last) 次。
[編輯] 可能的實現
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); // or 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) |
判斷一個範圍是否按給定謂詞劃分 (函式模板) |