C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ find()

C++ 算法函数find()

C++ 算法find()函数在参数列表中指定一个值,在范围内搜索该值,迭代器启动从第一个元素开始搜索并继续到last元素,如果在范围内找到该元素,则返回该元素,否则给出范围的last元素。

语法

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

参数

first: 它指定范围的第一个元素。
last: 指定范围的last元素。
value: 指定在范围内搜索的值。

返回值

该函数将迭代器返回到等于该值的范围的第一个元素。如果找不到这样的元素,则该函数返回last元素。

示例1

#include <iostream>     
#include <algorithm>    
#include <vector>       
int main ()
{ 
  int newints[] = { 50, 60, 70, 80 };
  int * q;
 q = std::find (newints, newints+4, 60);
 if (q != newints+4)
 std::cout << "Element found in newints: " << *q << '\n';
  else
    std::cout << "Element not found in newints\n";
  std::vector<int> newvector (newints,newints+4);
  std::vector<int>::iterator ti;
  ti = find (newvector.begin(), newvector.end(), 60);
  if (ti != newvector.end())
   std::cout << "Element found in newvector: " << *ti << '\n';
  else
    std::cout << "Element not found in newvector\n";
 return 0;
}
输出:
Elements that are found in newints: 60
Elements that are found in newvector: 60

示例2

#include<iostream>
#include<algorithm>
#include<vector>
int main()
{
    std:: vector<int> vct {50,60,70,80}; 
    std::vector<int>::iterator ti;
    std::cout<<"Initial vector:";
    for(int k=0; k<vct.size(); k++)
    std::cout<<" "<<vct[k];
        std::cout<<"\n";
    int sr = 60;
    
    ti = std::find(vct.begin(), vct.end(),sr);
    if(ti!=vct.end())
    {
        std::cout<< "The element "<<"has been found at position:";
        std::cout<<ti-vct.begin() +1<<"\n";
    }
    else
        std::cout<<"Element does not exist.\n \n";
    return 0;
}
输出:
Intitial vector: 50 60 70 80
The element 30 has been found  at position: 2

复杂度

该函数以线性方式移动,从第一个元素开始到last元素。对于列表中的每个元素,都会检查" pred"的值。搜索继续进行,直到遇到与" pred"值不匹配的地方。

数据竞争

指定范围内的所有对象或其中某些对象都是

异常

如果任何参数抛出一个异常,该函数就会引发异常。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4