一:功能
检查一个序列是否已按条件分组,第二个参数指定了分组的条件
二:用法
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> data{2, 4, 6, 7, 9, 11};
auto is_even = [](int v) { return v % 2 == 0; };
bool test1 = std::ranges::is_partitioned(data, is_even);
std::cout << std::boolalpha << "is_partitioned(is_even) == " << test1 << "\n";
bool test2 = true;
for (int i = 0; i < 16; ++i) {
test2 = test2 && std::is_partitioned(data.begin(), data.end(),
[&i](int v) { return v < i; });
}
std::cout << std::boolalpha << "is_sorted() == " << test2 << "\n";
}
三:实现
#include <vector>
#include <algorithm>
#include <array>
#include <iostream>
template<class InputIt, class UnaryPred>
bool my_is_partitioned(InputIt first, InputIt last, UnaryPred p)
{
for (; first != last; ++first)
if (!p(*first))
break;
for (; first != last; ++first)
if (p(*first))
return false;
return true;
}
int main()
{
std::array<int, 9> v {1, 2, 3, 4, 5, 6, 7, 8, 9};
auto is_even = [](int i) { return i % 2 == 0; };
std::cout.setf(std::ios_base::boolalpha);
std::cout << my_is_partitioned(v.begin(), v.end(), is_even) << ' ';
std::partition(v.begin(), v.end(), is_even);
std::cout << my_is_partitioned(v.begin(), v.end(), is_even) << ' ';
std::reverse(v.begin(), v.end());
std::cout << my_is_partitioned(v.cbegin(), v.cend(), is_even) << ' ';
std::cout << my_is_partitioned(v.crbegin(), v.crend(), is_even) << '\n';
}