• STL算法之find


    定义

    template <class InputIterator, class T>
    InputIterator find (InputIterator first, InputIterator last, const T& val);
    

    作用

    在范围[first, last]之间查找第一个等于val的元素。找到则返回第一个匹配元素的iterator,否则返回last迭代器。
    此函数使用operator==来逐个比较元素和val。
    改函数模板等效如下:

    template<class InputIterator, class T>
      InputIterator find (InputIterator first, InputIterator last, const T& val)
    {
      while (first!=last) 
      {
        if (*first==val) 
        {
            return first;
        }
        ++first;
      }
      return last;
    }
    

    参数

    first,last

    输入迭代器,分别作为squence起始和终止位置。在范围[first,last)内搜索,包含first,不包含last

    val

    在范围内搜索的值。T是支持和InputIterator通过操作符==进行比较操作的类型(元素在操作符的左边,val在其右边)

    返回值

    当==比较操作为true时,返回第一个元素的迭代器。否则返回last

    示例

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int main( int argc, char **argv )
    {
        vector<int>::iterator ret;
        vector<int> numbers{1, 2, 7, 2,3};
    
        //出现一次
        ret = find(numbers.begin(), numbers.end(), 1);
        if ( ret == numbers.end() )
        {
            cout << "not found 1" << endl;
        }
        else
        {
            cout << "found 1" << endl;
        }
    
        //出现多次
        ret = find(numbers.begin(), numbers.end(), 2);
        if ( ret == numbers.end() )
        {
            cout << "not found 2" << endl;
        }
        else
        {
            //找到的是第一个元素
            cout << "found 2 and next element is:"<< *(ret+1) << endl;
        }
    
        //未出现
        ret = find(numbers.begin(), numbers.end(), 5);
        if ( ret == numbers.end() )
        {
            cout << "not found 5" << endl;
        }
        else
        {
            cout << "found 5" << endl;
        }
    
        return 0;
    }
    
  • 相关阅读:
    ubuntu中mysql版本升级到5.7
    ng-深度学习-课程笔记-5: 深层神经网络(Week4)
    ng-深度学习-课程笔记-4: 浅层神经网络(Week3)
    《计算机程式设计》Week6 课堂笔记
    《计算机程式设计》Week5 课堂笔记
    关于解决coursera视频缓冲问题
    《计算机程式设计》Week4 课堂笔记
    《计算机程式设计》Week3 课堂笔记
    《计算机程式设计》Week2 课堂笔记
    使用 Matlab 运行 Windows 命令
  • 原文地址:https://www.cnblogs.com/thammer/p/11205089.html
Copyright © 2020-2023  润新知