简单的程序诠释C++ STL算法系列之二:find

本文介绍了C++ STL中find算法的功能与使用方法。find算法用于在一序列中查找指定值的第一个匹配项,并返回对应的迭代器。文章通过示例代码展示了如何在实际应用中使用find算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    C++STL的非变易算法(Non-mutating algorithms)是一组不破坏操作数据的模板函数,用来对序列数据进行逐个处理、元素查找、子序列搜索、统计和匹配。

     find算法用于查找等于某值的元素。它在迭代器区间[first , last)上查找等于value值的元素,如果迭代器iter所指的元素满足 *iter == value ,则返回迭代器iter,未找则返回last。

函数原型:

[cpp]  view plain copy
  1. template<class InputIterator, class Type>  
  2.    InputIterator find(  
  3.       InputIterator _First,   
  4.       InputIterator _Last,   
  5.       const Type& _Val  
  6.    );  

示例代码:

[cpp]  view plain copy
  1. /******************************************************************* 
  2.  * Copyright (C) Jerry Jiang              
  3.  * File Name   : find.cpp 
  4.  * Author      : Jerry Jiang 
  5.  * Create Time : 2011-9-29 0:03:25 
  6.  * Mail        : jbiaojerry@gmail.com 
  7.  * Blog        : http://blog.youkuaiyun.com/jerryjbiao  
  8.  * Description :  简单的程序诠释C++ STL算法系列之二              
  9.  *                非变易算法 : 查找容器元素find             
  10.  ******************************************************************/  
  11.   
  12. #include <algorithm>  
  13. #include <list>  
  14. #include <iostream>  
  15.   
  16. using namespace std;  
  17.   
  18. int main()  
  19. {  
  20.     list<int> ilist;  
  21.     for (size_t i = 0; i < 10; ++i)  
  22.     {  
  23.         ilist.push_back(i+1);  
  24.     }  
  25.   
  26.     ilist.push_back(10);  
  27.   
  28.     list<int>::iterator iLocation = find(ilist.begin(), ilist.end(), 10);  
  29.   
  30.     if (iLocation != ilist.end())  
  31.     {  
  32.         cout << "找到元素 10" << endl;  
  33.     }  
  34.   
  35.     cout << "前一个元素为:" << *(--iLocation) << endl;  
  36.   
  37.     return 0;  
  38. }  

*******************************************************************************************************************************

C++经典书目索引及资源下载:http://blog.youkuaiyun.com/jerryjbiao/article/details/7358796

********************************************************************************************************************************

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值