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

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

技术教程推荐

许式伟的架构课 -〔许式伟〕

JavaScript核心原理解析 -〔周爱民〕

接口测试入门课 -〔陈磊〕

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

Redis核心技术与实战 -〔蒋德钧〕

PyTorch深度学习实战 -〔方远〕

遗留系统现代化实战 -〔姚琪琳〕

高并发系统实战课 -〔徐长龙〕

AI绘画核心技术与实战 -〔南柯〕

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