for_each

With for_each function in algorithm header I can manipulate each element of a vector increase 3 by the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>
#include <algorithm> // for_each
void incre(int&);
using namespace std;
int main(){
	int arr[]={3,4,2};
	for_each(arr,arr+3,incre);
	for (int i=0;i<3;++i){
		cout<<arr[i]<<"\t";
	}
	cout<<endl;
}
void incre(int& i){
	i+=3;
}


My question is: if I can customize the amount I want to increase for each element (still using for_each) how can I do?
Thank you.

My question is: if I can customize the amount I want to increase for each element (still using for_each) how can I do?
1
2
3
void incre(int& i){
	i+=3;
}

Simply change the amount you want to increment in this function.
In order to change that value from main() you may use lambda functions:

http://en.cppreference.com/w/cpp/language/lambda
I would use a function object( functor).
http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html

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
#include <iostream>
#include <algorithm> // for_each

using namespace std;

class Incrementer
{
public:
  Incrementer(int amount)
  {
    m_Amount = amount;
  }

  void operator()(int& i)
  {
    i += m_Amount;
  }
private:
  int m_Amount;
};

int main() 
{
  int arr [] = { 3,4,2 };

  Incrementer inc(5);

  for_each(arr, arr + 3, inc);

  for (int i = 0; i<3; ++i) 
  {
    cout << arr[i] << "\t";
  }
  cout << endl;

  system("pause");
  return 0;
}
I would use a function object( functor).
... over a lambda? Really?
I would use a function object( functor).
... over a lambda? Really?

No not really, this example is actually too trivial for a functor, unless to need compatibility with older compiler.
Topic archived. No new replies allowed.