• C++ STL 常用查找算法


    C++ STL 常用查找算法

    adjacent_find()

    在iterator对标识元素范围内,查找一对相邻重复元素,找到则返回指向这对元素的第一个元素的迭代器。否则返回past-the-end。

    vector<int> vecInt;
    vecInt.push_back(1);
    vecInt.push_back(2);
    vecInt.push_back(2);
    vecInt.push_back(4);
    vecInt.push_back(5);
    vecInt.push_back(5);

    vector<int>::iterator it = adjacent_find(vecInt.begin(), vecInt.end());  //*it == 2

    binary_search

    在有序序列中查找value,找到则返回true。注意:在无序序列中,不可使用。
    set<int> setInt;
    setInt.insert(3);
    setInt.insert(1);
    setInt.insert(7);
    setInt.insert(5);
    setInt.insert(9);
    bool bFind = binary_search(setInt.begin(),setInt.end(),5);

    count()

    利用等于操作符,把标志范围内的元素与输入值比较,返回相等的个数。
    vector<int> vecInt;
    vecInt.push_back(1);
    vecInt.push_back(2);
    vecInt.push_back(2);
    vecInt.push_back(4);
    vecInt.push_back(2);
    vecInt.push_back(5);
    int iCount = count(vecInt.begin(),vecInt.end(),2); //iCount==3

    count_if()

    假设vector<int> vecIntA,vecIntA包含1,3,5,7,9元素
    //先定义比较函数
    bool GreaterThree(int iNum)
    {
           if(iNum>=3)
           {
                  return true;
           }
           else
           {
                  return false;
           }
    }
    int iCount = count_if(vecIntA.begin(), vecIntA.end(), GreaterThree); //此时iCount == 4

    find()

    find: 利用底层元素的等于操作符,对指定范围内的元素与输入值进行比较。当匹 配时,结束搜索,返回该元素的迭代器。
    equal_range: 返回一对iterator,第一个表示lower_bound,第二个表示 upper_bound。

    vector<int> vecInt;
    vecInt.push_back(1);
    vecInt.push_back(3);
    vecInt.push_back(5);
    vecInt.push_back(7);
    vecInt.push_back(9);
    vector<int>::iterator it = find(vecInt.begin(), vecInt.end(), 5); //*it == 5


    find_if()

    find_if: 使用输入的函数代替等于操作符执行find。返回被找到的元素的迭代器。
    假设vector<int> vecIntA,vecIntA包含1,3,5,3,9元素
    vector<int>::it = find_if(vecInt.begin(),vecInt.end(),GreaterThree);
    此时 *it==3, *(it+1)==5, *(it+2)==3, *(it+3)==9 

  • 相关阅读:
    数据结构之排序七:归并排序
    数据结构之排序六:快速排序
    在MFC中显示cmd命令行
    一次性无重复配置VS项目插件属性的方法
    mysql & vs2013
    matlab 图像Mat类型矩阵中的值(uint8)类型转换,防止溢出
    利用vs10和opencv识别图片类型身份证的号码
    static
    Filter2D卷积运算
    opencv 矩阵类数据的运算
  • 原文地址:https://www.cnblogs.com/lsgxeva/p/7793352.html
Copyright © 2020-2023  润新知