Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function on every element of a C++ vector

In C++, is there a way to call a function on each element of a vector, without using a loop running over all vector elements? Something similar to a 'map' in Python.

like image 906
vikaspraj Avatar asked May 09 '12 12:05

vikaspraj


1 Answers

Yes: std::for_each.

#include <algorithm> //std::for_each  void foo(int a) {     std::cout << a << "\n"; }  std::vector<int> v;  ...  std::for_each(v.begin(), v.end(), &foo); 
like image 68
Oliver Charlesworth Avatar answered Sep 18 '22 00:09

Oliver Charlesworth