算法库-排列操作

is_permutation()

判断一个序列是否为另一个序列的排列
头文件
< algorithm >
函数
constexpr bool is_permutation( ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2 );

若存在范围 [first1, last1) 中元素的排列,使得该范围等于 [first2,last2) ,则返回 true ,若不给出,则其中 last2 代表 first2 + (last1 - first1) 。

返回值
若范围 [first1, last1) 是 [first2, last2) 的排列则为 true 。

#include<iostream>
#include <algorithm>
#include<vector>
using namespace std;
int main() {
    vector<int> v1{1, 2, 3, 4, 5};
    vector<int> v2{2, 4, 3, 1, 5};
    vector<int> v3{1, 2, 4, 5, 6};
    cout << "{1, 2, 3, 4, 5} is a permutation of {2, 4, 3, 1, 5} ?"
    << boolalpha//把1变成true
    << is_permutation(v1.begin(), v1.end(), v2.begin()) //返回1或0
    << endl;
    
    cout << "{1, 2, 3, 4, 5} is a permutation of {1, 2, 4, 5, 6} ?"
    << boolalpha
    << is_permutation(v1.begin(), v1.end(), v3.begin()) << endl;
    return 0;
}

运行效果

{1, 2, 3, 4, 5} is a permutation of {2, 4, 3, 1, 5} ?true
{1, 2, 3, 4, 5} is a permutation of {1, 2, 4, 5, 6} ?false

next_permutation

产生某个元素范围的按字典顺序的下一个较大的排列
头文件
< algorithm >

函数

bool next_permutation( BidirIt first, BidirIt last, Compare comp );

变换范围 [first, last) 为来自所有按相对于 operator< 或 comp 的字典序的下个排列。若这种排列存在则返回 true ,否则变换范围为首个排列(如同用 std::sort(first, last) )并返回 false 。

返回值
若新排列按字典序大于旧者则为 true 。若抵达最后重排并重置范围为首个排列则为 false 。

代码演示

#include<iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    string s = "aca";
    sort(s.begin(), s.end());
    do {
        cout << s << endl;
    } while(next_permutation(s.begin(), s.end()));
    
    return 0;
}

运行结果

aac
aca
caa

prev_permutation

产生某个元素范围的按字典顺序的下一个较小的排列
(函数模板)

定义于头文件
(1)
template< class BidirIt, class Compare >
bool prev_permutation( BidirIt first, BidirIt last, Compare comp);
变换范围 [first, last) 为来自于相对于 operator< 或 comp 的字典序的所有排列集合的上个排列。若这种排列存在则返回 true ,否则变换范围为末排列(如同用 std::sort(first, last); std::reverse(first, last); )并返回 false;

代码演示

#include<iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    string s = "aca";
    sort(s.begin(), s.end(), greater<char>());
    do {
        cout << s << endl;
    } while(prev_permutation(s.begin(), s.end()));
    
    return 0;
}

运行结果

caa
aca
aac
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值