c++ stl algorithm: std::find, std::find_if

std::find:

    查找容器元素, find仅仅能查找容器元素为<基本数据类型>

   

  1. #include <iostream>  
  2. #include <vector>  
  3. #include <algorithm>  
  4. int main()  
  5. {  
  6.     std::vector<int> v;  
  7.     for (int i = 0; i < 10; ++i)  
  8.         v.push_back(i);  
  9.     std::vector<int>::iterator iter = std::find(v.begin(), v.end(), 3);  
  10.     if (iter == v.end())  
  11.         std::cout << "can not find value 3 in v" << std::endl;  
  12.     else  
  13.         std::cout << "the index of value " << (*iter) << " is " << std::distance(v.begin(), iter) << std::endl;  
  14.     return 0;  
  15. }  

 

 

std::find_if

    按条件查找容器元素, 容器类型为<类>时, 无法使用find来查找,  所以要使用find_if来查找

   

  1. #include <iostream>  
  2. #include <vector>  
  3. #include <algorithm>  
  4. #include <functional>  
  5. struct Point  
  6. {  
  7.     int x;  
  8.     int y;  
  9. };  
  10. struct PointFindByCoord : public std::binary_function<Point, Point, bool>  
  11. {  
  12.     bool operator () (const Point &obj1, const Point &obj2) const  
  13.     {  
  14.         return obj1.x == obj2.x && obj1.y == obj2.y;  
  15.     }  
  16. };  
  17. int main()  
  18. {  
  19.     std::vector<Point> v;  
  20.     for (int i = 0; i < 5; ++i)  
  21.     {  
  22.         for (int j = 0; j < 5; ++j)  
  23.         {  
  24.             Point pt;  
  25.             pt.x = i;  
  26.             pt.y = j;  
  27.             v.push_back(pt);  
  28.         }  
  29.     }  
  30.     Point needFind;  
  31.     needFind.x = 4;  
  32.     needFind.y = 3;  
  33.     std::vector<Point>::iterator iter = std::find_if(v.begin(), v.end(), std::bind2nd(PointFindByCoord(), needFind));  
  34.     if (iter == v.end())  
  35.     {  
  36.         // 未找到  
  37.     }  
  38.     else  
  39.         std::cout << "the index of value Point(" << (*iter).x << ", " << (*iter).y  
  40.             << ") is " << std::distance(v.begin(), iter) << std::endl;  
  41.       
  42.     return 0;  
  43. }  

 



转会:http://blog.csdn.net/ilysony/article/details/6526545

posted @ 2015-07-04 18:26  blfshiye  阅读(185)  评论(0编辑  收藏  举报