std::find:
查找容器元素, find仅仅能查找容器元素为<基本数据类型>
[cpp] view
plaincopy
plaincopy
- #include <iostream>
- #include <vector>
- #include <algorithm>
- int main()
- {
- std::vector<int> v;
- for (int i = 0; i < 10; ++i)
- v.push_back(i);
- std::vector<int>::iterator iter = std::find(v.begin(), v.end(), 3);
- if (iter == v.end())
- std::cout << "can not find value 3 in v" << std::endl;
- else
- std::cout << "the index of value " << (*iter) << " is " << std::distance(v.begin(), iter) << std::endl;
- return 0;
- }
std::find_if
按条件查找容器元素, 容器类型为<类>时, 无法使用find来查找, 所以要使用find_if来查找
[cpp] view
plaincopy
plaincopy
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <functional>
- struct Point
- {
- int x;
- int y;
- };
- struct PointFindByCoord : public std::binary_function<Point, Point, bool>
- {
- bool operator () (const Point &obj1, const Point &obj2) const
- {
- return obj1.x == obj2.x && obj1.y == obj2.y;
- }
- };
- int main()
- {
- std::vector<Point> v;
- for (int i = 0; i < 5; ++i)
- {
- for (int j = 0; j < 5; ++j)
- {
- Point pt;
- pt.x = i;
- pt.y = j;
- v.push_back(pt);
- }
- }
- Point needFind;
- needFind.x = 4;
- needFind.y = 3;
- std::vector<Point>::iterator iter = std::find_if(v.begin(), v.end(), std::bind2nd(PointFindByCoord(), needFind));
- if (iter == v.end())
- {
- // 未找到
- }
- else
- std::cout << "the index of value Point(" << (*iter).x << ", " << (*iter).y
- << ") is " << std::distance(v.begin(), iter) << std::endl;
- return 0;
- }