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

原文地址:http://blog.csdn.net/ilysony/article/details/6526545

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

#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来查找

#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;
}

原文链接: https://www.cnblogs.com/zhuyf87/archive/2013/03/13/2957572.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/80478

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午7:34
下一篇 2023年2月9日 下午7:35

相关推荐