如何通过STL算法获得两个数组(向量)的组合? [英] How to get combination of two array ( vector ) by STL algorithm?
本文介绍了如何通过STL算法获得两个数组(向量)的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 v1
和 v2
,我应该如何获得新的 v
如下所示?
I have v1
and v2
, how should I got a new v
like below?
v1 = {1,2}
v2 = {3,4,5}
v = {f(1,3) , f(1,4) , f(1,5) f(2,3) ,f(2,4) ,f(2,5)}
我知道我可以使用两个循环来做到这一点,但是如果还有更多惯用的方式,例如使用STL算法?
I know I could do it using two loops, But If there is more idiomatic way like using STL algorithm?
//using two loops
for iter1 of v1
for iter2 of v2
v.push_back(f(v1,v2))
编辑:
v1
和 v2
的大小不必相同。
推荐答案
没有合适的STL算法,但是可以通过自定义函数和std :: generate:
There is no appropriate STL algorithm, but this combination possible to do by a custom function and std::generate:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
typedef int T;
struct Fctor
{
typedef std::vector<T>::iterator Iterator;
Iterator it1, it2, begin, end;
Fctor(Iterator begin1, Iterator end1, Iterator begin2)
{
begin = begin1;
end = end1;
it1 = begin1;
it2 = begin2;
}
T operator()()
{
// T result = f(*it1, *it2);
T result = (*it1) * (*it2);
if(++it1 != end) return result;
it1 = begin;
++ it2;
return result;
}
};
int main()
{
std::vector<T> v1; v1.push_back(1); v1.push_back(2);
std::vector<T> v2; v2.push_back(3); v2.push_back(4); v2.push_back(5);
std::vector<T> result(v1.size() * v2.size());
Fctor fctor(v2.begin(), v2.end(), v1.begin());
generate(result.begin(), result.end(), fctor);
std::copy(result.begin(), result.end(),
std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
// => 3 4 5 6 8 10
}
这篇关于如何通过STL算法获得两个数组(向量)的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文