
next_permutation介绍
用于生成某个序列的下一个排列。它通常在需要生成排列的问题中使用,比如全排列问题。
使用方法
普通序列 :next_permutation(起始地址,末尾地址+1)
结构体:next_permutation(起始地址,末尾地址+1,自定义排列)
例子
对于普通数组
int main()
{
	int a[4] = { 1,2,3,4 };
	do {
		for (auto i : a)
		{
			cout << i << " ";
		}
		cout << endl;
	} while (next_permutation(a, a + 4));
	return 0;
}
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
对于vector等容器
int main()
{
	vector<int>v{ 1,2,3,4 };
	do {
		for (auto i : v)
		{
			cout << i << " ";
		}
		cout << endl;
	} while (next_permutation(v.begin(), v.end()));
	return 0;
}
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
对于结构体
 需要自定义比较函数
struct test {
	int val;
};
bool cmp(test t1, test t2) {
	return t1.val < t2.val;
}
int main() {
	test t[3];    
	t[0].val = 1;    
	t[1].val = 2;    
	t[2].val = 3;    
	do {
		for (int i = 0;i < 3;i++) {//打印排列     
			cout << t[i].val << ' ';    
		}
		cout << endl;    
	} while (next_permutation(t, t + 3, cmp));//获取下一个排列     
}
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
本篇完!



















