在字符数组上使用next_permutation

Using next_permutation on a array of chars

本文关键字:next permutation 字符 数组      更新时间:2023-10-16

我在以空结尾的字符数组上使用next_permutation时遇到了问题。当我登录 do while 语句时,它只给了我开始的 charArray 的第一个字符,而不是给我所有可能的排列的第一个字符。 这是代码:

void generatePermutations(int no_ones, int length){
    char charArray[length+1];
    for(int i = 0; i < length; i++){
        if(no_ones > 0){
            charArray[i] = '1';
            no_ones--;
        }else{
            charArray[i] = '0';
        }
    }
    charArray[length] = '';
    do {
        std::cout << charArray[0] << std::endl;
    } while ( std::next_permutation(charArray, (charArray + length)));
}

如果要使用规范do ... while(std::next_permutation)循环来访问所有排列,则需要初始化数组,使其按排序顺序排列。这样做的原因是std::next_permutation算法计算当前排列之后按字典顺序排列的排列。在您的情况下,您以反向排序顺序开始数组,因此算法将在第一次返回 false。

您可以更改代码以初始化数组,也可以保留它并事先添加对std::reverse的调用。