Julien Lopez
Julien Lopez

Reputation: 1021

algorithm to add values of two ranges and place them into a third one

I was just wondering if there was anything (either in c++11 or boost) that could help me do something like this:

std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {2, 5, 4};
std::list<int> res;
algorithm(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(res), std::plus<int>());

the result should of course be {3, 7, 7} and where instead of std::plus could be any binary_function.

So if anyone has an idea, let me know.

Upvotes: 7

Views: 524

Answers (4)

Jerry Coffin
Jerry Coffin

Reputation: 490098

Just for fun, I'll point to an alternative to std::vector and std::transform. You could use std::valarray instead.

#include <valarray>
#include <iostream>

int main() { 
    std::valarray<int> a = {1, 2, 3};
    std::valarray<int> b = {2, 5, 4};

    std::valarray<int> c = a + b;    // look ma, no transform!

    for (int i=0; i<3; i++)
        std::cout << c[i] << "\t";
}

Result:

3       7       7

Unfortunately, even though the code for adding the valarrays together is simple and clean, valarray has never gained much popularity. As such, we're left with this rather strange situation where even code like that above that strikes me as very clean, straightforward and readable still almost qualifies as obfuscated, simply because so few people are accustomed to it.

Upvotes: 12

juanchopanza
juanchopanza

Reputation: 227390

You can use the 5 parameter overload of std::transform for this. This takes a binary functor to operate on pairs of elements of two ranges:

std::transform(v1.begin(), 
               v1.end(), 
               v2.begin(), 
               back_inserter(res), 
               std::plus<int>());

Upvotes: 9

piwi
piwi

Reputation: 5336

std::transform (http://en.cppreference.com/w/cpp/algorithm/transform) is what you might be looking for.

Upvotes: 4

Asha
Asha

Reputation: 11232

std::transform is what you are looking for.

Upvotes: 4

Related Questions