C++ find

函数原型:

template<class InputIterator, class T>
  InputIterator find ( InputIterator first, InputIterator last, const T& value )
  {
    for ( ; first != last ; first++) if ( *first == value ) break;
    return first;
  }
返回区间 [ first , end ] 中第一个值等于 value 的元素的位置。

如果没有找到匹配元素,则返回 end。

复杂度:线性复杂度。最多比较次数:元素的总个数。

程序实例:

下面的程序在 int 类型的 vector 中搜寻元素 5 和 12,如果搜索到,就返回其位置 , 否则输出提示信息。

Main.cpp:

#include <iostream>
#include <vector>
#include <algorithm>  //find 需要 
using namespace std ;

template < class T >		//模板  
inline void INSERT_ELEMENTS( T &col , int first , int last )
{
	for( int i = first ; i <= last ; i++ )
		col.insert( col.end() , i ) ;
}

int main()
{
	vector<int> Ivec ;
	INSERT_ELEMENTS( Ivec , 1 , 9 ) ;
	vector<int>::iterator pos ;		//迭代器  
	pos = find( Ivec.begin() , Ivec.end() , 5 ) ;		//查找5 
	if( pos == Ivec.end() ) 				//没找到 
		cout << " 5 不存在。\n" ;
	else {
		cout << " 5 存在 , 位置 " <<
		distance(Ivec.begin() , pos ) + 1 << endl ;		
	}
	pos = find( Ivec.begin() , Ivec.end() , 12 ) ;
	if( pos == Ivec.end() ) 
		cout << " 12 不存在。\n" ;
	else {
		cout << " 12 存在 , 位置 " <<
		distance(Ivec.begin() , pos ) + 1 << endl ;		
	}
	return 0 ;
}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值