C++ 重载==运算符,判断结构体是否相等 使用find()查找vector中是否存在某个结构体struct元素

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;
    }
    
    
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值