簡體   English   中英

next_permutation 不是通過引用?

[英]next_permutation not by reference?

我不明白為什么在循環內部,position 的值發生了變化。 但是在外面do, while loop ,所有的值都回到原來的位置。 因此我需要//here代碼。 我也嘗試了一個指針數組,但它表現出相同的行為。 為什么這樣?

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int a[] = {0, 1, 2};
    do
    {
        for (int i = 0; i < 3; i++)
            cout << a[i];
        cout << endl;
    } while (next_permutation(a, a + 3));
    cout << endl;
    // here
    a[0] = 2;
    a[1] = 1;
    a[2] = 0;

    do
    {
        for (int i = 0; i < 3; i++)
            cout << a[i];
        cout << endl;
    } while (prev_permutation(a, a + 3));
    return 0;
}

這就是next_permutation的定義方式。 最后一種排列(返回 false 的排列)是將元素按排序順序排列的排列。

我想還有一個誤解。 這里:

do
{
    print_permutation();
} while (next_permutation(a, a + 3));

您在循環內打印的最后一個排列是使next_permutation返回false的排列之前的排列。 因此,在最后一次迭代中,您不會打印與循環外相同的排列。 它類似於:

bool increment(int& i) {
    ++i;
    return i<10;
}

int i = 0;
do {
   std::cout << i;
} while( increment(i) );

std::cout << i;

循環內打印的最后一個值是9 ,但循環后i的值是10

每次調用它時, std::next_permutation都會為給定容器a生成一個排列P' ,其中當前排列是P 只要它生成的排列P'大於P ,它就會返回true 然而,在P是給定容器a中元素的最大排列(即,參見下文以了解偉大的解釋)的情況下,例如P=[2, 1, 0]它生成的下一個排列P'[0, 1, 2] ,不大於P 在這種情況下,它返回false並且循環終止。 但是,由於該過程的副作用,一旦 function 返回,容器中的元素已經被放置在可能的最小排列中。 這就是為什么您會在循環終止后看到這些元素的最小排列。

更大這個詞可能有點令人困惑。 基本上std::next_permutation使用任何可用的比較運算符來比較單個元素,並最終以隨着每個后續排列按字典順序增加的方式對它們進行迭代。 因此,對於[0, 1, 2]的向量,它將按該順序迭代以下排列:

0, 1, 2
0, 2, 1
1, 0, 2
1, 2, 0
2, 0, 1
2, 1, 0

這就是為什么 function 認識到[0,1,2][2,1,0]之后不會更大的排列並返回 false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM