C++实用函数:find与find_if

发布于:2025-03-25 ⋅ 阅读:(70) ⋅ 点赞:(0)

本篇来介绍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

网站公告

今日签到

点亮在社区的每一天
去签到