Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

4 Answers

up vote 8 down vote accepted

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>());
share|improve this answer
oh ok I didn't know there was a version with five parameters. I should have looked better, thanks a lot all. – Julien Lopez 2 days ago
+1 for resisting the temptation to use a lambda when there's already a std functor for it. – Christian Rau 2 days ago

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.

share|improve this answer
+1 ah really cool, I didn't know that it was a vectorized array. I take it it also works with all the other arithmetic operators. – TemplateRex 2 days ago
ah, didn't know that existed either, could come in handy someday. – Julien Lopez 2 days ago
@TemplateRex: Yeah, pretty much all of them. You can also do things like valarray + int to add a number to each member of the valarray (e.g., in the example, above, c + 1 would give 4 8 8). – Jerry Coffin 2 days ago

std::transform is what you are looking for.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.