千峰 c++ _STL库中 迭代器 (1)算法中的for_each和迭代器的联合使用

算法for_each中的迭代器用法

在算法中for_each中是遍历的意思
机构for_each(InIt _First,InIt _Last,_Func)
其中_First 和 _Last是相关的迭代器参数,而_Func是函数的入口地址参数。

for_each 其中for代表循环,each代表每一个,这个算法代表遍历。
因为不明白需要遍历函数来需要哪些操作,就需要自己写动作函数,并把它的函数入口地址传入,for_each中

例如 void print(int a)
{
cout << a <<endl;
}
for_each(it_start,it_end,print);
在这里插入图片描述
其中包括了 相关算法的类模板。

相关的实验代码:
#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传入的是函数的入口地址。

cout << endl;

}

int main(){
example();
return 0;
}

这个表明了其中迭代器的用法。

猜你喜欢

转载自blog.csdn.net/qq_45788043/article/details/108857676