要在std::vector
中的自定义对象上使用std::find
,你需要提供一个比较函数或者重载自定义对象的==
运算符。以下是两种方法的详细说明和示例代码。
==
运算符首先,你需要确保你的自定义对象可以进行相等比较。这通常通过重载==
运算符来实现。
#include <iostream>
#include <vector>
#include <algorithm>
class MyClass {
public:
int id;
std::string name;
// 重载 == 运算符
bool operator==(const MyClass& other) const {
return id == other.id && name == other.name;
}
};
int main() {
std::vector<MyClass> vec = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
MyClass target = {2, "Bob"};
// 使用 std::find 查找对象
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout << "Found: " << it->name << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
如果你不想或不能重载==
运算符,你可以提供一个自定义的比较函数给std::find
。
#include <iostream>
#include <vector>
#include <algorithm>
class MyClass {
public:
int id;
std::string name;
};
// 自定义比较函数
bool compareMyClass(const MyClass& a, const MyClass& b) {
return a.id == b.id && a.name == b.name;
}
int main() {
std::vector<MyClass> vec = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
MyClass target = {2, "Bob"};
// 使用 std::find 和自定义比较函数查找对象
auto it = std::find_if(vec.begin(), vec.end(), [&target](const MyClass& obj) {
return compareMyClass(obj, target);
});
if (it != vec.end()) {
std::cout << "Found: " << it->name << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
std::find
通常实现为线性搜索,对于小型到中型数据集来说是高效的。==
运算符确保逻辑正确。==
运算符或比较函数不正确,可能会导致编译错误。确保所有必要的成员变量都被正确地比较。通过上述方法,你应该能够在std::vector
中的自定义对象上有效地使用std::find
。
领取专属 10元无门槛券
手把手带您无忧上云