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