tags:

views:

55

answers:

3

I'm currently trying to learn how to effectively use the STL part of c++. Say there are 2 vectors of the same type of equal length that need to be transformed into another vector of the same length by applying some operator, is there a good way to do this using the functionality of the STL?

Here's some pseudocode for what I'm trying to do:

vector<T> a;
vector<T> b;
vector<T> result;

for (int i = 0; i < a.size(); ++i){
    result.at(i) = a.at(i)  op  b.at(i);
}

where "op" is some operator that is defined for type T.

A: 

Ok, I may be wrong, but:

short answer : no

long answer : perhaps something clever should be done about it, but writing the code as a loop is much more readable.

It reminds me of the following problem :

"given a vector x and a vector y of same size, permute elements of x and y simultaneously such that y is sorted according to some predicate"

which I couldn't solve using some STL algorithm directly (except with cumbersome ad-hoc iterator classes, possibly made generic, but hard-writing a quick sort was way easier -- this is why I have a love-hate relationship with c++)

Alexandre C.
+5  A: 

You may need to do some checking on sizes, but generally you can use std::transform.

E.g. (for + - <functional> contains class templates for function objects for this and other binary operators)

std::transform( a.begin(), a.end(), b.begin(), result.begin(), std::plus<T>() );

You need to ensure that b.size() >= a.size() and result.size() >= a.size(). If result starts out empty then you can use a back_insert_iterator to fill it without having to resize the container first.

Charles Bailey
This is exactly the sort of solution I was looking for. In this case result is starting as empty so what is the correct syntax for using back_insert_iterator ?
shuttle87
Ok I think I figured this out,#include <iterator>then use:std::transform( a.begin(), a.end(), b.begin(), back_inserter(result), std::plus<T>() ); Thanks for the good answer!
shuttle87
@shuttle87: Yes, I think that you are correct.
Charles Bailey
+3  A: 

You can use std::transform : http://www.cplusplus.com/reference/algorithm/transform/

fingerprint211b