码迷,mamicode.com
首页 > 其他好文 > 详细

【转】回调的原理、应用

时间:2016-09-27 19:23:14      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

 

 

 

什么是回调

  什么回调?维基百科是这样解释的:回调是一段可执行的代码通过参数传递给别一段代码,以期望在一个合适的时间调用这个参数(可执行的代码)。 

  参考:In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back(execute) the argument at some convenient time.

 

从一个需求开始

  假设有这么一个需求:

  有一个Person类定义如下:

struct Person
{
    int age;
    float weight;
    float height;
};

  现要对Person的一组对象进行排序,但并没有确定根据什么规则来排序,有时需要根据年龄进行排序,有时需要根据身高进行排序,有时可能是根据身高和体重的综合情况来排序,还有可能…… 

  你可能会想到这样写,定义三个函数分别根据年龄、体重、身高进行排序:

1 void SortByAge(Person* persons, int count);
2 void SortByWeight(Person* persons, int count);
3 void SortByHeight(Person* persons, int count);

  如果要根据身高和体重的综合情况来排序,那你还得再定义一个函数。这样是不是代码冗余且很繁琐?但如果你会用回调,这个问题就会很简单。 

用回调实现对Person的排序:

 1 typedef int (*Compare)(const Person&, const Person&);  
 2    
 3 //交换两个元素  
 4 void swap(Person* p1, Person *p2)  
 5 {  
 6     Person p = *p1;  
 7     *p1 = *p2;  
 8     *p2 = p;  
 9 }  
10 //排序(本例中采用冒泡排序)  
11 void PersonSort(Person* persons, int count, Compare pCompare)  
12 {  
13     for (int i = 0; i < count-1; i ++)  
14     {  
15         for (int j = 0; j < count - i -1; j++)  
16         {  
17             if (pCompare(persons[j], persons[j+1]) > 0)  
18             {  
19                 swap(persons+j, persons+j+1);  
20             }  
21         }  
22     }  
23 }  

  如果你要根据年龄来进行排序,只要实现一个Compare类型的函数,再调用上面的PersonSort函数就可以实现根据年龄排序的功能。如:

 1 //根据年龄排序
 2 int CompareByAge(const Person& p1, const Person& p2)  
 3 {  
 4     return p1.age - p2.age;  
 5 }  
 6    
 7 void TestCallBack()  
 8 {  
 9     //创建Person的一组对象persons,对象中的年龄、体重值为0到100的随机数,身高为150-190之间的随机数  
10     srand((unsigned)time(NULL));   
11     Person persons[10];  
12     for(int i = 0; i < 10; i ++)  
13     {  
14         persons[i].age = rand()%100;  
15         persons[i].weight = rand()%100;  
16         persons[i].height = rand()%40 +150;  
17     }  
18     //【todo】  
19     //根据年龄进行排序。  
20     PersonSort(persons, 10, CompareByAge);  
21       
22     for(int i = 0; i < 10; i ++)  
23     {  
24         std::cout << persons[i].age << "\t" <<    persons[i].weight << "\t" << persons[i].height << std::endl;  
25     }  
26 }  

 

  这样如果需求发生变更(如要根据每个Person身高和体重的总和来排序),只需要再定义一个Compare类型的函数,而不用再对PersonSort函数做任何改动。如下:

 1 //只需要再定义一个Compare类型的函数实现按身高体重来排序,其余部分无需改动
 2 int CompareByHeightWeight(const Person& p1, const Person& p2)  
 3 {  
 4     return (p1.height + p1.weight) - (p2.height + p2.weight);  
 5 }  
 6    
 7 void TestCallBack()  
 8 {  
 9     //创建Person的一组对象persons,对象中的年龄和体重为0到100的随机数,身高为150-190之间的随机数  
10     srand((unsigned)time(NULL));   
11     Person persons[10];  
12     for(int i = 0; i < 10; i ++)  
13     {  
14         persons[i].age = rand()%100;  
15         persons[i].weight = rand()%100;  
16         persons[i].height = rand()%40 +150;  
17     }  
18     //【todo】  
19     //根据年龄进行排序。  
20     PersonSort(persons, 10, CompareByHeightWeight);  
21       
22     for(int i = 0; i < 10; i ++)  
23     {  
24         std::cout << persons[i].age << "\t" <<    persons[i].weight << "\t" << persons[i].height << "\t" << persons[i].weight + persons[i].height << std::endl;  
25     }  
26 }  

 

 

  C++ STL中的Sort(在<algorithm>头文件中)用的就是这种技术:

template<class RandomAccessIterator>
     void sort(
        RandomAccessIterator first, 
        RandomAccessIterator last
     );
  template<class RandomAccessIterator, class Predicate>
     void sort(
        RandomAccessIterator first, 
        RandomAccessIterator last, 
        Predicate comp
     );

 

  Parameters


 first

    A random-access iterator addressing the position of the first element in the range to be sorted.

 last

    A random-access iterator addressing the position one past the final element in the range to be sorted.

 comp

    User-defined predicate function object that defines the comparison criterion to be satisfied by successive elements in the ordering. This binary predicate takes two arguments and returns true if the two     arguments are in order and false otherwise. This comparator function must impose a strict weak ordering on pairs of elements from the sequence. For more information, see Algorithms. 

   

 

 

  回调函数说白了就是定义一个函数,然后通过参数传递给另一个函数调用。回调不仅是一种技术,更是一种编程思想,上面是通过回调函数来实现的,但它不仅限于回调函数,也可以用其它的技术实现(如面向对象的实现)。

  

【转】回调的原理、应用

标签:

原文地址:http://www.cnblogs.com/codingmengmeng/p/5913821.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!