所有可以再次用作数字的数字的排列

Permutations of all the digits that can be used as a number again

在 C++ 中,如果我需要在我的代码中进一步使用这些排列作为数字,那么生成某些数字的所有数字排列的最佳方法是什么?

假设我有这个 int n = 12345。我需要生成所有排列,e。 G。 12354、12435 等,并能将它们用作数字。

当然,我可以提取每个数字,将所有数字放入一个向量中,然后 运行 std::next_permutation,但这似乎很残酷-强加给我。还有更优雅的吗?

"best" C++ 解决方案是使用专门为所需目的设计的 C++ 元素/算法。而且,如果你想进行排列,那么 std::next_permutation 就是你要走的路。

因此,我们首先将值转换为字符串,然后获取所有排列并将每个排列转换为数字。有了这个数字,我们就可以工作了。

请看:

#include <algorithm>
#include <string>
#include <iostream>

int main()
{
    // Some test number
    constexpr unsigned int number{ 54321 };

    // Convert to string and sort the digits
    std::string s{ std::to_string(number) };
    std::sort(s.begin(), s.end());

    // Work with all permutations
    do {
        // Get the associated value
        unsigned long value{ std::stoul(s) };

        // Do what ever you want with the value
        std::cout << value << "\n";

    } while (std::next_permutation(s.begin(), s.end()));
}

请注意:至少有 42 种其他解决方案,在代码大小、速度或您可能有的任何要求方面可能有更好的解决方案。 . .