Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++中find函数的使用方法

作者:寒江映月   发布日期:2026-02-03   浏览:11

#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // 包含find函数的头文件

using namespace std;

int main() {
    // 示例1: 在字符串中查找字符
    string str = "Hello, World!";
    char targetChar = 'W';
    auto it_char = find(str.begin(), str.end(), targetChar);

    if (it_char != str.end()) {
        cout << "找到字符 '" << *it_char << "' 在位置: " << distance(str.begin(), it_char) << endl;
    } else {
        cout << "未找到字符 '" << targetChar << "'" << endl;
    }

    // 示例2: 在vector中查找元素
    vector<int> numbers = {1, 2, 3, 4, 5};
    int targetNumber = 3;
    auto it_num = find(numbers.begin(), numbers.end(), targetNumber);

    if (it_num != numbers.end()) {
        cout << "找到数字 " << *it_num << " 在位置: " << distance(numbers.begin(), it_num) << endl;
    } else {
        cout << "未找到数字 " << targetNumber << endl;
    }

    return 0;
}

解释说明:

  • find 函数用于在容器(如 stringvector 等)中查找指定的元素。
  • find 的返回值是一个迭代器,指向找到的第一个匹配元素。如果未找到,则返回容器的 end() 迭代器。
  • distance 函数用于计算两个迭代器之间的距离,从而确定元素的位置。
  • 示例1展示了如何在字符串中查找字符,示例2展示了如何在 vector 中查找整数。

上一篇:c++集合

下一篇:c++ abs函数

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

c++virtual

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站