当前位置: 首页 > news >正文

C++实用函数:find与find_if

本篇来介绍C++中find和find_if函数的使用,通过多个实例来演示。

find用于基础的查找功能,find_if可以实现更复杂的匹配查找条件。

1 find

1.1 函数原型

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

1.2 在vector中查找

find通常用于在vector中查找是否存在指定的元素。

//g++ test1.cpp -std=c++11 -o test1
#include <unistd.h>
#include <stdio.h>
#include <vector>
#include <algorithm>

int main()
{
	printf("hello\n");

	std::vector<int> numberList = {1, 3, 5, 7, 8, 9};
	
	int num = 7;

	// 循环查找
	for (int &it : numberList)
	{
		if (it == num)
		{
			printf("find num:%d in numberList\n", it);
			break;
		}
	}

	// find方式查找
	auto it = std::find(numberList.begin(),numberList.end(),num);
	if (it != numberList.end())
	{
		printf("find num:%d in numberList\n", *it);
	}

	return 0;
}

运行结果:

1.3 查找字符串

find也可用于在字符串查找字符和子串。

//g++ test2.cpp -std=c++11 -o test2
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <algorithm>

int main()
{
	printf("hello\n");

	std::string s1 = "hello world, hello c++";

	auto r1 = s1.find('l');
	auto r2 = s1.find('a');
	auto r3 = s1.find("ll");
	auto r4 = s1.find("abc");

    if (r1 != std::string::npos) 
	{
        printf("r1: 字符 'l' 首次出现的位置是 %zu\n", r1);
    } 
	else 
	{
        printf("r1: 未找到字符 'l'\n");
    }

    if (r2 != std::string::npos

相关文章:

  • 智能汽车图像及视频处理方案,支持视频星轨拍摄能力
  • 【机器学习基础 4】 Pandas库
  • 移植原包ROM通用处理方案
  • 作业12 (2023-05-15 指针概念)
  • Hostapd2.11解析笔记_nl80211接口交互流程_消息收发细节解析
  • vue js给元素动态添加动画样式, 改变背景色
  • 仓库管理4大核心系统(OMS、WMS、WCS、WES)是什么,有何用处?
  • 【系统架构设计师】DNS查询过程
  • Linux基础 -- SoC从uboot到linux kernel的全过程
  • 从感知器准则到最小平方误差准则——与神经网络的发展类比
  • 使用Python可视化图结构:从GraphML文件生成节点关系图(lightrag 生成)
  • FPGA中串行执行方式之流水线(Pipeline)
  • 大数据学习(84)-Hive数仓
  • IIS漏洞攻略
  • C# 属性(Property)‌详解
  • 了解TikTok直播不推流的原因及流量异常的解决方案
  • 基于SpringBoot的电影售票系统
  • spring和maven
  • 内网渗透基础
  • 稳健投资新标杆,云济会布局国库券回购助推金融市场优化
  • 《水饺皇后》领跑五一档票房,《哪吒2》上座率仍居第一
  • 停电催生商机,中国品牌 “照亮” 西班牙
  • 新华时评:防范安全事故须臾不可放松
  • 过去24小时中美是否就关税问题进行过接触?外交部:没有
  • 中央网信办部署开展“清朗·整治AI技术滥用”专项行动
  • 城市更新·简报│中央财政支持城市更新,倾斜超大特大城市