C++ vector 的所有组合

标签 c++ algorithm c++11 boost stl

假设我们有一些从 0 到 n 的数字,我们想要打乱那些大小为 s 的数字,并希望看到所有可能的组合。

所以排列的数量恰好等于s! * n!/(s!*(n-s)!)

n = 3s = 3 的示例:

0 1 2 | 0 1 3 | 0 2 1 | 0 2 3 | 0 3 1 | 0 3 2 | 1 0 2 | 1 0 3 | 1 3 2 
1 2 3 | 1 2 0 | 1 3 0 | 2 0 1 | 2 1 0 | 2 0 3 | 2 3 0 | 2 3 1 | 2 1 3
            3 0 1 | 3 1 0 | 3 0 2 | 3 2 0 | 3 1 2 | 3 2 1

是否有使用 boost/STL 的平滑方法来实现此目的?

最佳答案

这是使用 T.C. 链接的代码评论中提到的 ( http://howardhinnant.github.io/combinations.html ):

#include "../combinations/combinations"
#include <iostream>
#include <vector>

int
main()
{
    std::vector<int> v{0, 1, 2, 3};
    typedef std::vector<int>::iterator Iter;
    for_each_permutation(v.begin(), v.begin()+3, v.end(),
        [](Iter f, Iter l)
        {
            for (; f != l; ++f)
                std::cout << *f << ' ';
            std::cout << "| ";
            return false;
        }
    );
    std::cout << '\n';
}

0 1 2 | 0 2 1 | 1 0 2 | 1 2 0 | 2 0 1 | 2 1 0 | 0 1 3 | 0 3 1 | 1 0 3 | 1 3 0 | 3 0 1 | 3 1 0 | 0 2 3 | 0 3 2 | 2 0 3 | 2 3 0 | 3 0 2 | 3 2 0 | 1 2 3 | 1 3 2 | 2 1 3 | 2 3 1 | 3 1 2 | 3 2 1 | 

这个库相对于 std::next_permutation 的一个显着优势是被置换的元素不需要排序,甚至不需要小于可比性。例如:

#include "../combinations/combinations"
#include <iostream>
#include <vector>

enum class color
{
    red,
    green,
    blue,
    cyan
};

std::ostream&
operator<< (std::ostream& os, color c)
{
    switch (c)
    {
    case color::red:
        os << "red";
        break;
    case color::green:
        os << "green";
        break;
    case color::blue:
        os << "blue";
        break;
    case color::cyan:
        os << "cyan";
        break;
    }
    return os;
}

int
main()
{
    std::vector<color> v{color::blue, color::red, color::cyan, color::green};
    typedef std::vector<color>::iterator Iter;
    for_each_permutation(v.begin(), v.begin()+3, v.end(),
        [](Iter f, Iter l)
        {
            for (; f != l; ++f)
                std::cout << *f << ' ';
            std::cout << "| ";
            return false;
        }
    );
    std::cout << '\n';
}

blue red cyan | blue cyan red | red blue cyan | red cyan blue | cyan blue red | cyan red blue | blue red green | blue green red | red blue green | red green blue | green blue red | green red blue | blue cyan green | blue green cyan | cyan blue green | cyan green blue | green blue cyan | green cyan blue | red cyan green | red green cyan | cyan red green | cyan green red | green red cyan | green cyan red |

关于C++ vector 的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25827750/

相关文章:

c++ - 如何为 Visual Studio Clang-Format 插件提供 clang 格式文件?

c++ - 如何在 C++ 中注释正则表达式?

由于函数调用,SQL 索引变慢

上下文无关文法的算法

c++ - 从 STL 迭代器非公开派生的自定义迭代器的最小功能?

c++ - 为什么允许从 pair<int64_t,int64_t> 到 pair<int,int> 的隐式转换?

c++ - 为什么这个 PP_ARG_COUNT 宏需要一个 PP_EXPAND?

c++ - 如何在不使用指针的情况下将动态二维数组传递给函数?

javascript - 粒子淡入淡出

c++ - 在没有 #define 的情况下捕获 __LINE__ 和 __FILE__