for_each(iterator,iterator,callback);
前两个参数列表是遍历容器的迭代器,第三个参数是对应的回调函数
回调函数的原理都是将参数传递至相应的函数体,再进行操作
# include<iostream>
# include<algorithm>
# include<vector> using namespace std;void Print(int val)
{cout << val << " ";
}/*
基本数据类型
遍历算法
*/
void test1()
{vector<int> v;v.push_back(1);v.push_back(5);v.push_back(4);v.push_back(2);v.push_back(6);for_each(v.begin(),v.end(),Print);} /*
自定义数据类型
for_each遍历
*/
class Person{public:Person(int a,int b):index(a),age(b){}public:int age;int index;
};void Print2(Person &p)
{cout << "index:" << p.index << " " << "age:" << p.age << endl;
}void test2()
{vector<Person> vp;Person p1(1,4),p2(2,5),p3(3,6);vp.push_back(p1);vp.push_back(p2);vp.push_back(p3);for_each(vp.begin(),vp.end(),Print2);
}int main()
{//test1();test2();return 0;
}
test1:
test2:
本文发布于:2024-01-29 07:00:58,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170648286113533.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |