

新闻资讯
技术学院std::vector没有内置find成员函数,需用中的std::find线性查找元素,返回匹配迭代器或end();自定义类型需重载==;复杂条件用std::find_if配合谓词;有序时应改用二分查找优化。
在 C++ 中,std::vector 本身没有内置的 find 成员函数,但可以借助标准算法库中的 std::find 在 vector 中查找元素。它返回一个迭代器,指向第一个匹配项,若未找到则返回 end()。
std::find 定义在 头文件中,适用于任意支持随机/前向迭代的容器。对 std::vector 来说,效率是线性时间 O(n)。
基本用法:
begin() 和 end() 迭代器作为搜索范围vec.end() 来判断是否找到示例:
立即学习“C++免费学习笔记(深入)”;
#include
#include
#include
std::vectorv = {10, 20, 30, 40, 30};
auto it = std::find(v.begin(), v.end(), 30);
if (it != v.end()) {
std::cout << "找到,索引为: " << (it - v.begin()) << "\n"; // 输出 2
} else {
std::cout << "未找到\n";
}
若 vector 存储的是自定义结构体或类,需确保该类型支持 == 比较操作符。
例如:
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
std::vectorpeople = {{"Alice", 25}, {"Bob", 30}};
auto it = std::find(people.begin(), people.end(), Person{"Bob", 30});
当查找逻辑更复杂(如“年龄大于 28 的人”),应改用 std::find_if,配合 lambda 或函数对象:
示例:
立即学习“C++免费学习笔记(深入)”;
auto it = std::find_if(v.begin(), v.end(), [](int x) { return x % 10 == 0 && x > 25; });
// 查找大于 25 且能被 10 整除的数,会找到 30 或 40
std::find 总是顺序扫描,不依赖排序。若 vector 已排序且需高效查找,应考虑:
std::sort 排序,再用 std::binary_search(仅判断存在性)std::lower_bound + 比较,获取位置并验证相等性但这些不是 s 的替代,而是不同场景下的优化选择。
td::find