开发者

How to get combination of two array ( vector ) by STL algorithm?

开发者 https://www.devze.com 2022-12-08 08:14 出处:网络
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)}

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)}

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))

EDIT:

v1 and v2 not necessary have same size.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消