#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 函数用于在容器(如 string、vector 等)中查找指定的元素。find 的返回值是一个迭代器,指向找到的第一个匹配元素。如果未找到,则返回容器的 end() 迭代器。distance 函数用于计算两个迭代器之间的距离,从而确定元素的位置。vector 中查找整数。上一篇:c++集合
下一篇:c++ abs函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站