std::for_each

closed account (S879Nwbp)
Hello,

Is std::for_each faster than c++ for and in a for_each statement how can I determine the current value of the iterator and the value of the vector from that iterator?

e.g

#include <vector>

vector<int> Vector1;

std::for_each(Vector1.begin(), Vector1.end(), myfunction) {

it = ?;

int i = Vector1.it; ?

}

Thankyou.

Did you look at: http://www.cplusplus.com/reference/algorithm/for_each/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <algorithm>
#include <vector>

void myfunction (int i) { // here is your 'int i'
  std::cout << ' ' << i;
}

int main () {
  std::vector<int> myvector;
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(30);

  for_each( myvector.begin(), myvector.end(), myfunction );
  std::cout << '\n';

  for ( int x : myvector )
    myfunction( x );
  std::cout << '\n';

  for ( auto it = myvector.begin(); it < myvector.end(); ++it )
    myfunction( *it );
  std::cout << '\n';

  for_each( myvector.begin(), myvector.end(), [](int i){std::cout << ' ' << i;} );
  std::cout << '\n';

  for ( int i : myvector )
    std::cout << ' ' << i;
  std::cout << '\n';

  for ( size_t it = 0; it < myvector.size(); ++it ) {
    int i = myvector[it];
    std::cout << ' ' << i;
  }
  std::cout << '\n';

  return 0;
}



A loop is a loop. There might be some implementation-specific differences on efficiency.
Topic archived. No new replies allowed.