std::is_permutation
定义于头文件 <algorithm> |
||
template< class ForwardIt1, class ForwardIt2 > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, |
(1) | (自 C++11 起) (constexpr 自 C++20 起) |
template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > |
(2) | (自 C++11 起) (constexpr 自 C++20 起) |
template< class ForwardIt1, class ForwardIt2 > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, |
(3) | (自 C++14 起) (constexpr 自 C++20 起) |
template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > |
(4) | (自 C++14 起) (constexpr 自 C++20 起) |
检查 [
first1,
last1)
是否是由 first2 开始的范围的排列
- 对于重载 (1,2),第二个范围有 std::distance(first1, last1) 个元素。
- 对于重载 (3,4),第二个范围是
[
first2,
last2)
。
如果 ForwardIt1
和 ForwardIt2
拥有不同的值类型,则程序是病式的。
如果比较函数不是等价关系,则行为未定义。
内容 |
[编辑] 参数
first1, last1 | - | 定义要比较的第一个范围的元素的迭代器对 |
first2, last2 | - | 定义要比较的第二个范围的元素的迭代器对 |
p | - | 二元谓词,若元素应被视作相等则返回 true。 谓词函数的签名应等价于以下形式 bool pred(const Type1 &a, const Type2 &b); 虽然签名不需要拥有 const &,函数仍不得修改传递给它的对象,且必须能接受类型(可能为 const)为 |
类型要求 | ||
-ForwardIt1, ForwardIt2 必须满足 LegacyForwardIterator 的要求。 |
[编辑] 返回值
若范围 [
first1,
last1)
是范围 [
first2,
last2)
的排列则为 true,否则为 false。
[编辑] 复杂度
设 N 为 std::distance(first1, last1)
) 次比较。
) 次。
ForwardIt1
和 ForwardIt2
均为 LegacyRandomAccessIterator,且 last1 - first1 != last2 - first2 为 true,则不进行比较。) 次比较。
) 次。
[编辑] 可能的实现
template<class ForwardIt1, class ForwardIt2> bool is_permutation(ForwardIt1 first, ForwardIt1 last, ForwardIt2 d_first) { // skip common prefix std::tie(first, d_first) = std::mismatch(first, last, d_first); // iterate over the rest, counting how many times each element // from [first, last) appears in [d_first, d_last) if (first != last) { ForwardIt2 d_last = std::next(d_first, std::distance(first, last)); for (ForwardIt1 i = first; i != last; ++i) { if (i != std::find(first, i, *i)) continue; // this *i has been checked auto m = std::count(d_first, d_last, *i); if (m == 0 || std::count(i, last, *i) != m) return false; } } return true; } |
[编辑] 注意
std::is_permutation
能用于测试,即检查重排算法(如排序、洗牌、划分)的正确性。若 x
为原范围而 y
为已排列范围,则 std::is_permutation(x, y) == true 意味着 y
由“相同的”元素构成,可能处于不同的位置。
[编辑] 示例
#include <algorithm> #include <iostream> template<typename Os, typename V> Os& operator<<(Os& os, const V& v) { os << "{ "; for (const auto& e : v) os << e << ' '; return os << '}'; } int main() { static constexpr auto v1 = {1, 2, 3, 4, 5}; static constexpr auto v2 = {3, 5, 4, 1, 2}; static constexpr auto v3 = {3, 5, 4, 1, 1}; std::cout << v2 << " is a permutation of " << v1 << ": " << std::boolalpha << std::is_permutation(v1.begin(), v1.end(), v2.begin()) << '\n' << v3 << " is a permutation of " << v1 << ": " << std::is_permutation(v1.begin(), v1.end(), v3.begin()) << '\n'; }
输出
{ 3 5 4 1 2 } is a permutation of { 1 2 3 4 5 }: true { 3 5 4 1 1 } is a permutation of { 1 2 3 4 5 }: false
[编辑] 参见
生成范围中元素的下个更大的字典序排列 (函数模板) | |
生成范围中元素的下个更小的字典序排列 (函数模板) | |
(C++20) |
指明 relation 施加等价关系(概念) |
(C++20) |
确定一个序列是否为另一序列的排列 (算法函数对象) |