STL算法之find

定义

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

做用

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

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在其右边)spa

返回值

当==比较操做为true时,返回第一个元素的迭代器。不然返回lastcode

示例

#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;
}
相关文章
相关标签/搜索