#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void printVector(int v)
{
cout << v<<" ";
}
//STL基本语法
void test01()
{
//定义一个容器,并指定里面放的元素类型是int,v是这个容器的名字
//vector可以理解为一个动态(可变)数组,其空间会自行增加
vector<int>v;
v.push_back(10);//在容器的尾部插入
v.push_back(20);
v.push_back(30);
v.push_back(40);
//用STL提供的for_each算法
//迭代器由容器提供
//vector<int>::iterator为迭代器类型
vector<int>::iterator pBegin = v.begin();
vector<int>::iterator pEnd = v.end();
//for_each参数(迭代器1,迭代器2,回调函数) 关于为什么要用回调函数
//是因为容器中可能存放基础的数据类型,也可能存放自定义的数据类型,容器自己不知道怎么打印你自己写的比如类之类的,所以要自己写一个回调函数将其打印出来
for_each(pBegin, pEnd, printVector);
//也可以直接写for_each(v.begin,v.end,...),但是这样编译前在每次循环的时候都会调用begin和end函数,费时间
//for_each实质:
//template<typename InputIterator, typename Function>
//Function for_each(InputIterator beg, InputIterator end, Function f) {
//while(beg != end)
//f(*beg++);
}
}
//容器存放自定义的数据类型
class Person
{
public:
Person(string name, int age)
{
Name=name;
Age=age;
}
public:
string Name;
int Age;
};
void test02()
{
vector<Person>v;
Person p1("zzx",20),p2("yxy",40),p3("520",60);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
for (vector<Person>::iterator it = v.begin();it != v.end(); it++)
{
//*itBegin得到的类型是vector<Person>v里写的Person对象
cout << "name:" << (*it).Name <<" " << "age:" << (*it).Age << endl;
}
}
int main()
{
//test01();
test02();
}
什么是回调函数?
编程分为两类:系统编程(system programming)和应用编程(application programming)。所谓系统编程,简单来说,就是编写库;而应用编程就是利用写好的各种库来编写具某种功用的程序,也就是应用。系统程序员会给自己写的库留下一些接口,即API(application programming interface,应用编程接口
),以供应用程序员使用。所以在抽象层的图示里,库位于应用的底下。
当程序跑起来时,一般情况下,应用程序
(application program)会时常通过API调用库里所预先备好的函数。但是有些库函数(library function)却要求应用先传给它一个函数,好在合适的时候调用,以完成目标任务。这个被传入的、后又被调用的函数就称为回调函数(callback function
)。
打个比方,有一家旅馆提供叫醒服务,但是要求旅客自己决定叫醒的方法。可以是打客房电话,也可以是派服务员去敲门,睡得死怕耽误事的,还可以要求往自己头上浇盆水。这里,“叫醒”这个行为是旅馆提供的,相当于库函数,但是叫醒的方式是由旅客决定并告诉旅馆的,也就是回调函数。而旅客告诉旅馆怎么叫醒自己的动作,也就是把回调函数传入库函数的动作,称为登记回调函数(to register a callback function)。如下图所示(图片来源:维基百科
):
最后关于回调函数的解释转载如下
作者:no.body
链接:https://www.zhihu.com/question/19801131/answer/27459821
来源:知乎