C++ 算法 中的 find函数

首页 / C++入门教程 / C++ 算法 中的 find函数

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

find - 语法

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

find - 参数

first   - 它指定参数的第一个元素。

last    - 它指定参数的最后一个元素。

value - 它指定要在参数内搜索的值。

find - 返回值

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

find - 例子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

find - 例子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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

左耳听风 -〔陈皓〕

推荐系统三十六式 -〔刑无刀〕

玩转Spring全家桶 -〔丁雪丰〕

iOS开发高手课 -〔戴铭〕

Vue开发实战 -〔唐金州〕

罗剑锋的C++实战笔记 -〔罗剑锋〕

To B市场品牌实战课 -〔曹林〕

大厂设计进阶实战课 -〔小乔〕

快手 · 移动端音视频开发实战 -〔展晓凯〕

好记忆不如烂笔头。留下您的足迹吧 :)