Iter Ator
Iter Ator

Reputation: 9299

How to change the inserted value during the insertion?

I would like to insert the values from vector b to vector a, and multiply the values by -1 during the insertion. Currently I simply insert the elements, and multiply them by -1 afterwards:

a.insert(std::end(a), std::begin(b), std::end(b));
// ...

How is it possible to get the negative values already during the insertion, withoud modifying the original b vector?

What I would like to achieve:

old a = {2,3,4}
b = {3,4,5}

a = {2,3,4,-3,-4,-5}

Upvotes: 9

Views: 343

Answers (1)

lubgr
lubgr

Reputation: 38315

You can use std::transform like this:

#include <algorithm>

std::transform(std::cbegin(b), std::cend(b), std::back_inserter(a), std::negate<>());

Upvotes: 30

Related Questions