#include <iostream>
#include <vector>
#include <algorithm>
struct MyStruct {
int id;
std::string name;
// 自定义的相等判断谓词
bool operator==(const MyStruct& other) const {
return id == other.id && name == other.name;
}
};
int main() {
std::vector<MyStruct> vec = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
MyStruct target = {2, "Bob"};
auto it = std::find_if(vec.begin(), vec.end(), [&target](const MyStruct& s) {
return s == target;
});
if (it != vec.end()) {
int index = std::distance(vec.begin(), it);
std::cout << "Element found at index " << index << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
c++实现自己的类的相等判断,用于在容器中查找相同元素
最新推荐文章于 2024-07-14 15:36:20 发布