std::find()
可以用来查找vector中是否包含某个元素,但只能查找支持==
比较运算符的数据类型。如果你自定义了结构体struct或类class存入vector中,则不能直接用std::find()
查找。
- 可以在结构体struct、类class中重载
==
运算符使支持使用std::find()
#include <iostream>
#include <vector>
#include <algorithm>
struct MyData {
int id;
std::string name;
bool operator==(const MyData& another) const {
return (id == another.id && name == another.name);
}
};
int main() {
std::vector<MyData> v = {{1, "John"}, {2, "Mike"}, {3, "Tom"}};
// 查找 id 为 2 的元素
MyData target = {1, "John"};
if (std::find(v.begin(), v.end(), target) != v.end()) {
std::cout << "Found" << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
-
也可以使用
std::find_if()
, 自定义lambda函数作为判断相等的依据#include <iostream> #include <vector> #include <algorithm> struct MyData { int id; std::string name; }; int main() { std::vector<MyData> v = {{1, "John"}, {2, "Mike"}, {3, "Tom"}}; // 查找 id 为 2 的元素 int search_id = 2; auto iter = std::find_if(v.begin(), v.end(), [search_id](const MyData& d) { return d.id == search_id; }); if (iter != v.end()) { std::cout << "Found: " << iter->id << " " << iter->name << std::endl; } else { std::cout << "Not found" << std::endl; } return 0; }