Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}
like image 835
Iter Ator Avatar asked Jul 31 '18 12:07

Iter Ator


Video Answer


1 Answers

You can use std::transform like this:

#include <algorithm>

std::transform(std::cbegin(b), std::cend(b), std::back_inserter(a), std::negate<>());
like image 84
lubgr Avatar answered Oct 12 '22 23:10

lubgr