我有一个大小为“n”的整数向量。
e.g.
std::vector<int> vec;
vec.pushback(0);
vec.pushback(1);
vec.pushback(2);
vec.pushback(3);
....
现在我想生成size = {0,1,2,...,n}的所有可能组合。
请记住 {0,1,3}不等于{3,1,0}或{1,0,3}或{3,0,1}
如果您有任何想法,请帮助我。
提前致谢。
答案 0 :(得分:2)
你可以这样做:
#include<iostream>
#include<algorithm>
#include <vector>
std::ostream& operator<< (std::ostream& os, std::vector<int> v)
{
for (auto it = v.begin(); it != v.end(); ++it)
{
os << *it << ",";
}
return os;
}
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
do {
std::cout << v;
} while (std::next_permutation(v.begin(), v.end()));
}
根据@JamesKanze的评论,这只能在向量排序开始时才有效,所以如果你有一个未排序的向量,你应该首先在它上面调用std::sort
。
查看this,它说:
将范围[first,last]转换为相对于
operator<
或comp
按字典顺序排列的所有排列集的下一个排列。
您可以在行动here
中看到它