如何通过结构中的变量找出结构向量中是否存在结构

How to find out if a struct is present in a vector of structs by a variable within the struct

本文关键字:结构 向量 是否 存在 变量 何通过      更新时间:2023-10-16

我想检查向量中是否存在元素。我搜索了答案,我找到了这个

if (std::find(vector.begin(), vector.end(), item) != vector.end())
    do_this();
else
    do_that();

如果向量是类型结构怎么办。我们还能使用它来查找向量中是否存在匹配吗?我想使用结构条目中的字段 ID 在向量中找到。可能吗??

struct entry {
    int id;
    int array[4] = {};
    int aray[4] = {};
};

你需要的是std::find_if()

auto it = std::find_if(vec.begin(), vec.end(), [](S s) { return 5 == s.id; } );
if (vec.end() != it)
    do_this(); // it now points to the S instance found in the vector
else
    do_that();