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

C++ search()

C++ 算法函数search()

C++ 算法search()函数在范围[first1,last1)中搜索由范围[first2,last2)定义的子序列的出现,并返回第一个元素的迭代器。如果子序列不存在,则返回last1的迭代器。

语法

template<class ForwardIterator1, class ForwardIterator2> ForwardIterator1 search (ForwardIterator1 first1, ForwardIterator last1, ForwardIterator2 first2, ForwardIterator2 last2);
template<class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred);

参数

first1 : 它是[first1,last1)的第一个元素的正向迭代器。
last1 : 它是[first1,last1)的last元素的前向迭代器。
first2 : 它是第一个元素的前向迭代器。 [first2,last2)的元素。
pred : 它是一个二进制函数,接受两个元素作为参数并执行该函数设计的任务。

返回值

该函数将迭代器返回到子序列首次出现的第一个元素,否则返回last1元素。

示例1

#include <iostream> 
#include <algorithm>    
#include <vector>       
bool newpredicate (int m, int n) 
{
  return (m==n);
}
int main () 
{
  std::vector<int> haystack;
  for (int a=1; a<10; a++) haystack.push_back(a*10);
  int patt1[] = {20,30,40,50};
  std::vector<int>::iterator ti;
  ti = std::search (haystack.begin(), haystack.end(), patt1, patt1+4);
  if (ti!=haystack.end())
  std::cout << "patt1 found at position " << (ti-haystack.begin()) << '\n';
  else
  std::cout << "patt1 not found\n";
  int patt2[] = {40,35,50};
  ti = std::search (haystack.begin(), haystack.end(), patt2, patt2+3, newpredicate);
  if (ti!=haystack.end())
    std::cout << "patt2 found at position " << (ti-haystack.begin()) << '\n';
  else
  std::cout << "patt2 not found\n";
  return 0;
}
输出:
patt1 found at position 1
patt2 not found

示例2

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    int m, n;
    vector <int> u1={1,2,3,4,5,6,7};
    vector <int> u2={3,4,5};
    vector<int>::iterator ti;
    ti = std::search(u1.begin(), u1.end(),  u2.begin(),u2.end());
    if(ti!=u1.end())
    {
        cout<<"Vector2 is present at index:"<<(ti-u1.begin());
    }
    else
    {
        cout<<"In vector1, vector2 is not present";
    }
    return 0;
}
输出:
Vector2 is present at index:2

复杂度

该函数具有从first1元素到last1元素的线性复杂度。

数据竞争

访问两个范围内的对象。

异常

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

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