如何在 std::vector 内的自定义对象上使用 std::find? [英] How to use std::find on a custom object inside a std::vector?

查看:95
本文介绍了如何在 std::vector 内的自定义对象上使用 std::find?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在包含自定义对象的向量上使用 std::find但我不知道如何使用它来完成我想要做的事情.有没有其他方法可以做这种事情?

Trying to use std::find on a vector that contains custom objects but I can't figure out how to use it to accomplish what I'm trying to do. Is there another way to do this type of thing?

struct object
{
    char x;
    int y;
    object(char x, int y)
    {
        this->x = x;
        this->y = y;
    }
};

int main()
{
    std::vector<object> vector;

    object obj = object('X', 0);

    vector.push_back(obj);

    if (std::find(vector.begin(), vector.end(), ? ? ? ) != vector.end())
    {
        //do something
    }

    return 0;
}

我正在寻找 obj.y

推荐答案

std::find 算法有多个版本,其中一些您可以定义比较元素的方法.默认情况下,它将简单地使用相等比较==.

//         v----- found is not a boolean, but an iterator
auto const found = std::find(vector.begin(), vector.end(), element_to_find);

如果相等还不够,那么你可以使用 std::find_if 它接受一个谓词来比较元素:

If equality is not enough, then you could use std::find_if which accepts a predicate to compare elements:

auto const predicate = 
    [&](auto const& element) {
        return element.is_the_one(); // element.is_the_one() returns a boolean
                                     // You can use obj.y here
    };

//         v----- found is not a boolean, but an iterator
auto const found = std::find_if(vector.begin(), vector.end(), predicate);

我建议您阅读文档以了解如果使用 find 算法如何处理返回值.

I'd recommend reading the documentation in order to know how to handle the return value if the find algorithm.

这篇关于如何在 std::vector 内的自定义对象上使用 std::find?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆