Iterator usage in algorithm for_each
In the algorithm, for_each means traversal. The
mechanism for_each( InIt _First, InIt _Last, _Func)
where _First and _Last are related iterator parameters, and _Func is the entry address parameter of the function.
for_each where for stands for loop, each stands for each, and this algorithm stands for traversal.
Because I don’t understand what operations are needed to traverse the function, I need to write the action function myself and pass in its function entry address, in for_each
For example, void print(int a)
{ cout << a <<endl; } for_each(it_start,it_end,print); It includes class templates of related algorithms.
Related experimental code:
#include
#include
#include <string.h>
#include
using namespace std;
void print(int a){
cout << a <<endl;
}
void example(void){
vector v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
vector<int>::iterator it_start = v.begin();
vector<int>::iterator it_end = v.end();
/* for(; it_start != it_end; it_start++){ cout << *it_start << ""; } */ for_each(it_start,it_end,print); //print passed in is the entry address of the function.
cout << endl;
}
int main(){
example();
return 0;
}
This shows the usage of iterators.