与std :: vector的元素组合

Shi*_*bli 3 c++ combinations stl stdvector c++11

在下面的代码中,目的是foo组合调用每个元素vector<Grid> gr.是否有内置的STL功能,如果没有,对大型容器执行此操作的最佳方法是什么?注意,既然grid[0]影响grid[1]也是如此,grid[1]不应该调用该函数grid[0].所以,没有排列,只有组合.顺便说一句,这篇文章没有回答我的问题.

#include <iostream>
#include <vector>
using namespace std;

struct Grid
{
    void foo (Grid& g) {}
};

int main()
{
    vector<Grid> gr(3);
    gr[0].foo (gr[1]);
    gr[0].foo (gr[2]);
    gr[1].foo (gr[2]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

How*_*ant 6

这对于嵌套循环来说并不难,因为您只使用两个组合.话虽这么说,我最喜欢的库是这里记录的组合库:

http://howardhinnant.github.io/combinations.html

其中包含完整(和免费)的源代码.下面我展示了两种方式:

  1. 使用组合库.
  2. 编写自己的嵌套循环.

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

struct Grid
{
    int id_;

    Grid (int id) : id_(id) {}
    void foo (Grid& g)
    {
        std::cout << "Doing " << id_ << " and " << g.id_ << '\n';
    }
};

int main()
{
    std::vector<Grid> gr{0, 1, 2, 3};
    for_each_combination(gr.begin(), gr.begin()+2, gr.end(),
        [](std::vector<Grid>::iterator first, std::vector<Grid>::iterator last)
        {
            first->foo(*std::prev(last));
            return false;
        }
    );
    std::cout << '\n';
    for (unsigned i = 0; i < gr.size()-1; ++i)
        for (unsigned j = i+1; j < gr.size(); ++j)
            gr[i].foo(gr[j]);
}
Run Code Online (Sandbox Code Playgroud)

这输出:

Doing 0 and 1
Doing 0 and 2
Doing 0 and 3
Doing 1 and 2
Doing 1 and 3
Doing 2 and 3

Doing 0 and 1
Doing 0 and 2
Doing 0 and 3
Doing 1 and 2
Doing 1 and 3
Doing 2 and 3
Run Code Online (Sandbox Code Playgroud)

没有组合库的解决方案对于这种情况实际上更简单(一次取2个N个事物的组合).但是,随着一次采取的项目数量增加,或者如果这是运行时间信息,那么组合库真的开始获得它的保留.