标签:
看到有人問有個名為C的struct如下
code:
struct C { int v1; int v2; };
code:
bool Cfind75(const C& obj) { return obj.v2==75; }
code:
class Cfind75{ public: bool operator()(const C& obj) { return obj.v2==75; } };
code:
template<int n> class CComp{ public: bool operator()(const C& lhs) { return (lhs.v2==n); } };
code:
vector<C>::iterator cviter = find_if(cv.begin(),cv.end(),CComp<75>());
則cviter就是傳回cv中C型別物件的v2值為75的位置。
--
很簡單的小應用,也沒啥大學問。但是對STL不熟的往往都會忽略。
1 #include <iostream> 2 #include <algorithm> 3 #include <vector> 4 #include <cstdlib> 5 using namespace std; 6 struct C 7 { 8 C():v1(0),v2(0){} 9 C(const int& val1,const int& val2):v1(val1),v2(val2){} 10 C operator()(const int& val1,const int& val2) 11 { 12 v1=val1; 13 v2=val2; 14 return *this; 15 } 16 ~C(){} 17 int v1; 18 int v2; 19 }; 20 template<int n> 21 class CComp{ 22 public: 23 bool operator()(const C& lhs) 24 { 25 return (lhs.v2==n); 26 } 27 }; 28 int main(int argc, char *argv[]) 29 { 30 vector<C> cv; 31 C val; 32 cv.push_back(val(1,100)); 33 cv.push_back(val(2,52)); 34 cv.push_back(val(3,25)); 35 cv.push_back(val(4,75)); 36 cv.push_back(val(5,84)); 37 cv.push_back(val(6,33)); 38 39 vector<C>::iterator cviter = 40 find_if(cv.begin(),cv.end(),CComp<75>()); 41 cout<<cviter->v1<<" "<<cviter->v2<<endl; 42 cout<<endl; 43 44 system("PAUSE"); 45 return 0; 46 }
标签:
原文地址:http://www.cnblogs.com/zjoch/p/5738300.html