Wednesday, 15 January 2014

For each in C++, std::vector

Here it is an example code of using for each in c++ in three different ways. The code first initialises an array with values (1 2 4 5) and then it adds 1 to each one of its elements 3 times.
The output is : 4 5 7 8

//function that adds one to a given reference value
void addOne(int &n){n++;}

// function that prints all the elements of a given vector
void print(const std::vector &i_vec)
{
    for(const int &n: i_vec){std::cout << n << " ";}
    std::cout << "\n";
}

int main(void)
{
  //initialisation of an std::vector
  std::vector myvec{1,2,4,5};

  // first method of adding one to each of its elements
  for (int &n : myvec){n++;}
  // 2nd method
  std::for_each(myvec.begin(), myvec.end(),[](int &n){n++;});
  // 3rd method by calling the addOne function
  std::for_each(myvec.begin(), myvec.end(),addOne);

  // print the values of the array
  print(myvec);

  return 0;
}

No comments:

Post a Comment