当使用 std::find 函数在容器中查找特定元素时,如果找到该元素,将返回该元素的迭代器;如果找不到,将返回容器的 end 迭代器。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// 创建一个整数向量
std::vector<int> vec = {1, 2, 3, 4, 5};
// 在向量中查找特定的值
int target = 3;
auto it = std::find(vec.begin(), vec.end(), target);
// 检查是否找到了特定值
if (it != vec.end()) {
std::cout << "Element found in vector: " << *it << std::endl;
} else {
std::cout << "Element not found in vector" << std::endl;
}
return 0;
}
这个示例中,我们创建了一个整数向量 vec,并尝试查找值为 3 的元素。
如果找到了这个值,就会输出“Element found in vector: 3”。
如果在向量中找不到值为 3 的元素,将输出“Element not found in vector”。