编程语言
首页 > 编程语言> > C++ STL算法 is_partitioned(29)

C++ STL算法 is_partitioned(29)

作者:互联网

函数原型

template<class _InIt, class _Pr>
_NODISCARD inline bool is_partitioned(_InIt _First, _InIt _Last, _Pr _Pred)

测试范围内的元素是否是以pred为准则的一个划分。如果是,则返回true,否则返回false。

例如:T T T T F F F F或T T T或F F F或F F F T都算是一个划分。

但T F T或者F T F 就不是一个划分了。即满足pred的元素是否都在前面

参数

first, last 需要验证的函数范围

pred 自定义查找规则。该规则实际上是一个可包含 2 个参数且返回值类型为 bool 的函数(第一个参数接收 [first1, last1) 范围内的元素。函数定义的形式可以是普通函数,也可以是函数对象。

函数对象

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include <iterator>
#include <array>

bool IsEven(int a)
{
	return a % 2 == 0;
}

int main()
{	
	std::array<int, 9> v ={ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	
	std::cout.setf(std::ios_base::boolalpha);
	std::for_each(std::begin(v), std::end(v), [](int a) {std::cout << a << ", "; });
	std::cout << std::endl;

	std::cout << std::is_partitioned(v.begin(), v.end(), IsEven) << ' ' << std::endl << std::endl;

	std::partition(v.begin(), v.end(), IsEven);
	std::cout << "partition 分割后" << std::endl;
	std::for_each(std::begin(v), std::end(v), [](int a) {std::cout << a << ", "; });
	std::cout << std::endl;
	std::cout << std::is_partitioned(v.begin(), v.end(), IsEven) << ' ' << std::endl << std::endl;

	std::reverse(v.begin(), v.end());
	std::cout << "reverse 反序后" << std::endl;
	std::for_each(std::begin(v), std::end(v), [](int a) {std::cout << a << ", "; });
	std::cout << std::endl;
	std::cout << std::is_partitioned(v.cbegin(), v.cend(), IsEven) << ' ' << std::endl << std::endl;
	std::cout << std::is_partitioned(v.crbegin(), v.crend(), IsEven) << '\n';

	return -1;
}

1, 2, 3, 4, 5, 6, 7, 8, 9,
false

partition 分割后
8, 2, 6, 4, 5, 3, 7, 1, 9, //所有偶数在前面
true

reverse 反序后
9, 1, 7, 3, 5, 4, 6, 2, 8,
false

true

标签:std,函数,partitioned,STL,pred,C++,int,bool,include
来源: https://blog.csdn.net/qq_30460949/article/details/122299676