std::is_permutation
定义于头文件 <algorithm> |
||
template< class ForwardIt1, class ForwardIt2 > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, |
(1) | (C++11 起) (C++20 起为 constexpr) |
template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > |
(2) | (C++11 起) (C++20 起为 constexpr) |
template< class ForwardIt1, class ForwardIt2 > bool is_permutation( ForwardIt1 first1, ForwardIt1 last1, |
(3) | (C++14 起) (C++20 起为 constexpr) |
template< class ForwardIt1, class ForwardIt2, class BinaryPredicate > |
(4) | (C++14 起) (C++20 起为 constexpr) |
检查范围 [
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 &,但该函数绝不能修改传递给它的对象,且必须能接受 |
类型要求 | ||
-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) |
确定一个序列是否是另一个序列的排列 (算法函数对象) |