2009-10-10 6 views
1

J'ai v1 et v2, comment devrais-je obtenir un nouveau v comme ci-dessous?Comment obtenir la combinaison de deux tableau (vecteur) par l'algorithme STL?

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

Je sais que je pourrais le faire en utilisant deux boucles, mais s'il y a beaucoup plus idiomatiques comme l'utilisation de l'algorithme STL?

//using two loops 
for iter1 of v1 
    for iter2 of v2 
      v.push_back(f(v1,v2)) 

EDIT:

v1 et v2 ont pas même taille nécessaire.

+0

Qu'est-ce qu'un bon algorithme non récursif pour calculer un produit cartésien? : http://stackoverflow.com/questions/215908/whats-a-good-non-recursive-algorithm-to-calculate-a-cartesian-product – anno

+0

Cela ressemble presque exactement à ce que vous demandez: [http: //stackoverflow.com/questions/979436](http://stackoverflow.com/questions/979436) –

Répondre

1

Il n'y a pas d'algorithme approprié STL, mais cette combinaison possible de le faire par une fonction personnalisée et 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 
} 
Questions connexes