How to change the inserted value during the insertion?

  • A+
Category:Languages

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} 

 


You can use std::transform like this:

#include <algorithm>  std::transform(std::begin(b), std::end(b), std::back_inserter(a), std::negate<>()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: