STL算法之find
2024-10-06 08:04:55
定义
template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);
作用
在范围[first, last]之间查找第一个等于val的元素。找到则返回第一个匹配元素的iterator,否则返回last迭代器。
此函数使用operator==来逐个比较元素和val。
改函数模板等效如下:
template<class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
while (first!=last)
{
if (*first==val)
{
return first;
}
++first;
}
return last;
}
参数
first,last
输入迭代器,分别作为squence起始和终止位置。在范围[first,last)内搜索,包含first,不包含last。
val
在范围内搜索的值。T
是支持和InputIterator通过操作符==进行比较操作的类型(元素在操作符的左边,val在其右边)
返回值
当==比较操作为true时,返回第一个元素的迭代器。否则返回last。
示例
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main( int argc, char **argv )
{
vector<int>::iterator ret;
vector<int> numbers{1, 2, 7, 2,3};
//出现一次
ret = find(numbers.begin(), numbers.end(), 1);
if ( ret == numbers.end() )
{
cout << "not found 1" << endl;
}
else
{
cout << "found 1" << endl;
}
//出现多次
ret = find(numbers.begin(), numbers.end(), 2);
if ( ret == numbers.end() )
{
cout << "not found 2" << endl;
}
else
{
//找到的是第一个元素
cout << "found 2 and next element is:"<< *(ret+1) << endl;
}
//未出现
ret = find(numbers.begin(), numbers.end(), 5);
if ( ret == numbers.end() )
{
cout << "not found 5" << endl;
}
else
{
cout << "found 5" << endl;
}
return 0;
}
最新文章
- [No00009B]win10快捷键大全
- Maven命令
- Maven构件解析(转)
- Java基础之网络编程
- css3 钟表
- 【译】Android系统简介
- 04737_C++程序设计_第8章_多态性和虚函数
- asp.net mvc3 的数据验证(一)
- AOV网
- 解决CentOS虚拟机克隆后无法上网(网卡信息不一致)的问题
- Redis(三)-数据类型
- JAVA面向对象之重载与重写
- web前端学习历程--跨域问题
- sql server 查询某个表被哪些存储过程调用
- MySQL - 用户变量
- 【BI学习笔记】适合集成到项目里的BI:Wyn Enterprise
- 追求极致--纯css制作三角、圆形按钮,兼容ie6
- eclipse中jdk源码调试步骤
- 洛谷P2045 方格取数加强版(费用流)
- 20155334 网络对抗PC平台逆向破解(二)
热门文章
- iOS 开发之模糊效果的五种实现
- dnmp安装
- 流程控制 if----else
- 基于数组的shell脚本编写
- Computer Vision_33_SIFT:LIFT: Learned Invariant Feature Transform——2016
- Interval 用法总结
- 190906mysql常用语法
- 软件测试_Loadrunner_性能测试_脚本优化_关联_手动关联
- MyBatis3_[tp_41-42-43]-_动态sql_trim_自定义字符串截取_choose分支选择_update的set与if-trim 结合的动态更新
- maya 在 pymel 中运行 mel