Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用std::vector的元素进行组合_C++_C++11_Stl_Combinations_Stdvector - Fatal编程技术网

C++ 使用std::vector的元素进行组合

C++ 使用std::vector的元素进行组合,c++,c++11,stl,combinations,stdvector,C++,C++11,Stl,Combinations,Stdvector,在下面的代码中,目标是结合vector gr的每个元素调用foo。是否有内置STL功能?如果没有,对于大型容器,最好的方法是什么?请注意,由于grid[0]也会影响grid[1],grid[1]不应调用grid[0]上的函数。所以,没有排列,只有组合。顺便说一句,没有回答我的问题 #include <iostream> #include <vector> using namespace std; struct Grid { void foo (Grid&

在下面的代码中,目标是结合
vector gr
的每个元素调用
foo
。是否有内置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;
}
#包括
#包括
使用名称空间std;
结构网格
{
void foo(Grid&g){}
};
int main()
{
载体gr(3);
gr[0].foo(gr[1]);
gr[0].foo(gr[2]);
gr[1].foo(gr[2]);
返回0;
}

看起来您当然可以在这里使用嵌套循环,每个调用foo()中的两个整数对应一个。

使用嵌套循环并不难,因为您只使用两个整数的组合。话虽如此,我最喜欢的库是一个组合库,记录如下:

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

  • 使用组合库
  • 编写自己的嵌套循环


  • 对于这种情况,没有组合库的解决方案实际上更简单(N个事物的组合一次取2个)。然而,随着一次获取的项目数量的增加,或者如果这是运行时信息,那么组合库就真的开始赚钱了。

    可能的重复可能你可以用它的两个嵌套迭代来做某种巫术,要么使用
    for
    循环,要么使用
    std::for_each
    。哦!哦我做到了!现在我必须找到它!
    #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]);
    }
    
    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