Home > database >  Fastest way to add value to every element of vector<int>
Fastest way to add value to every element of vector<int>

Time:09-27

vector<int> v1{1,2,3,4};

I want to add 2 to every element of vector v1 without using loop and after execution the vector v1 must be v1{3,4,5,6}

CodePudding user response:

Here is a fast way without using loops:

v1[0]  = 2;
v1[1]  = 2;
v1[2]  = 2;
v1[3]  = 2;

The fastest way is the one that you have measured to be the fastest on your system.

CodePudding user response:

Unless the number of elements is hard-coded and you are willing to code the increment of each element individually, then a loop is required, eg:

#include <vector>

std::vector<int> v1;
...
for(int &elem){
    elem  = 2;
}

But, you don't have to code the loop manually, you can let the standard library handle it for you, eg:

#include <vector>
#include <algorithm>

std::vector<int> v1;
...
std::transform(v1.begin(), v1.end(), v1.begin(),
    [](int elem){ return elem   2; }
);

Alternatively:

#include <vector>
#include <algorithm>

std::vector<int> v1;
...
std::for_each(v1.begin(), v1.end(),
    [](int &elem){ elem  = 2; }
);
  •  Tags:  
  • c
  • Related