c++ 範型算法與函數對象 初認識


    一個很簡單的緣由:stl::vector 怎麼做加法。使用函數對象  

   函數對象的作用: 範型算法的實現獨立於容器類型,它消除了算法對類型的依賴,另一方面,當一個算法作用於一個具體的容器,如何建立聯繫? <--- 使用 函數對象

   通常,函數對象僅有一個成員函數,該函數重載函數調用操作符( operator() ), 函數對象作爲實參傳遞給範型算法。

   

  2 #include <assert.h>

  3 #include <numeric>

  4 using namespace std;

  5 

  6 #include "Vector.h"

  7 class MinusClass

  8 {

  9         public:

 10                 Vector2f operator() (Vector2f p1, Vector2f p2) const {return p1-p2;};

 11 };

 12 

 29         vector<Vector2f> NextPos (PositionVector.begin()+1, PositionVector.end());

 30         vector<Vector2f> LastPos (PositionVector.begin(),PositionVector.end()-1);

 31 

 32         assert(NextPos.size()==Num+1);

 33         assert(LastPos.size()==Num+1);

 34 

 35         vector<Vector2f> DeltaPos;

 36         transform(LastPos.begin(), LastPos.end(), NextPos.begin(), DeltaPos.begin(), MinusClass());

 37 

 38         for(vector<Vector2f>::iterator iter=DeltaPos.begin(); iter != DeltaPos.end(); iter++)

 39         {

 40                 float slope = (iter->z)/(iter->x);

 41                 bg_tang.push_back(normalize(Vector2f(1,slope)));

 42                 bg_normal.push_back(normalize(Vector2f(-slope,1)));

 43         }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章