Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1706764
  • 博文数量: 263
  • 博客积分: 1218
  • 博客等级: 少尉
  • 技术积分: 2862
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-19 02:33
文章分类

全部博文(263)

文章存档

2020年(12)

2019年(2)

2018年(10)

2016年(1)

2015年(20)

2014年(115)

2013年(46)

2012年(37)

2011年(20)

分类: C/C++

2014-09-22 10:05:32

转: http://blog.csdn.net/ilysony/article/details/6526545
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. }
1楼 mcadcj 2014-06-11 14:31发表    怎么可能find不能找类,是你自己的类没有定义operator == 。。。。

自己的类中定义了operator就可以???

阅读(1430) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~