#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 1Doing 0 and 2Doing 0 and 3Doing 1 and 2Doing 1 and 3Doing 2 and 3Doing 0 and 1Doing 0 and 2Doing 0 and 3Doing 1 and 2Doing 1 and 3Doing 2 and 3
没有组合库的解决方案对于这种情况实际上更简单(一次取2个N个事物的组合).但是,随着一次采取的项目数量增加,或者如果这是运行时间信息,那么组合库真的开始获得它的保留.
总结以上是内存溢出为你收集整理的c – 与std :: vector的元素组合全部内容,希望文章能够帮你解决c – 与std :: vector的元素组合所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)