C++<算法>排列算法>
为什么此代码注释有效(代码编译并运行良好,但实际上并未显示排列):
int main(int argc, char *argv[])
{
long number;
vector<long> interval;
vector<long>::const_iterator it;
cout << "Enter number: ";
cin >> number;
while(number-->0){
interval.push_back(number);
}
do{
for(it = interval.begin(); it < interval.end(); ++it){
cout << *it << " ";
}
cout << endl;
} while(next_permutation(interval.begin(), interval.end()));
return (0);
}
但是在更改此行之后:
while(next_permutation(interval.begin(), interval.end()));
with:
while(prev_permutation(interval.begin(), interval.end()));
排列不是通过作用于位置来更改向量中的元素吗?
PS: 我现在已经编辑了代码。
Why is this code note working (the code compiles and run fine, but is not actually showing the permutations):
int main(int argc, char *argv[])
{
long number;
vector<long> interval;
vector<long>::const_iterator it;
cout << "Enter number: ";
cin >> number;
while(number-->0){
interval.push_back(number);
}
do{
for(it = interval.begin(); it < interval.end(); ++it){
cout << *it << " ";
}
cout << endl;
} while(next_permutation(interval.begin(), interval.end()));
return (0);
}
But after changing this line:
while(next_permutation(interval.begin(), interval.end()));
with:
while(prev_permutation(interval.begin(), interval.end()));
Isn't permutation changing the elements in the vector by acting on positions ?
PS:
I've edited the code now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
排列是按字典顺序排列的,这就是
std:: next_permutation
和std::prev_permutation
算法遍历。在这里您输入“最大”排列,因此没有按顺序排列的下一个。
Permutations are lexicographically ordered, that's what
std::next_permutation
andstd::prev_permutation
algorithms traverse.Here you enter the "biggest" permutation, so there's no next one in order.
不会。
next_permutation
使用元素的排序来确定下一个排列。例如,如果A<A。 B< C,那么 [A,B,C] (012) 的
next_permutation
将是 [A,C,B] (021)。然而,如果A<A。 C< B,那么 [A,B,C] (021) 的next_permutation
将是 [C,A,B] (102)。由于您的向量最初是按降序排列的,因此它将是最后一个排列。
您可以使用
std::greater
顺序来反转比较方向。No.
next_permutation
uses the ordering of the elements to determine the next permutation.For example, if A < B < C, then the
next_permutation
of [A,B,C] (012) would be [A,C,B] (021). However, if A < C < B, then thenext_permutation
of [A,B,C] (021) would be [C,A,B] (102).Since your vector was initially in decreasing order, it would have been the last permutation.
You could use the
std::greater
ordering to reverse the comparison direction.我不认为 next_permutation 可以在位置上工作(它将在哪里存储该信息?)。您需要能够比较 next_permutation 才能工作的元素,这就是它用来生成按字典顺序排列的下一个排列的方法。
尝试以相反的顺序插入数字,看看是否有效。
I don't think next_permutation can work on positions (where will it store that info?). You need to be able to compare elements for next_permutation to work, and that is what it uses to generate the lexicographically next permutation.
Try inserting the numbers in the reverse order and see if that works.