在下面的代码中,目的是调用foo
。结合 vector<Grid> gr
的每个元素.是否有内置的 STL 功能,如果没有,对于大型容器,最好的方法是什么?请注意,由于 grid[0]
影响 grid[1]
同样,grid[1]
不应在 grid[0]
上调用函数.所以,没有排列,只有组合。顺便说一句,this post没有回答我的问题。
#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;
}
最佳答案
这对嵌套循环来说并不难,因为您只使用了两者的组合。也就是说,我最喜欢的库是一个组合库,记录在此处:
http://howardhinnant.github.io/combinations.html
其中包含完整(且免费)的源代码。下面我展示了两种方式:
- 使用组合库。
- 编写自己的嵌套循环。
#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
对于这种情况,没有组合库的解决方案实际上更简单(一次取 2 个 N 事物的组合)。然而,随着一次获取的项目数量的增加,或者如果这是运行时信息,那么组合库真正开始发挥作用。
关于c++ - 与 std::vector 的元素进行组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24963771/