简体   繁体   中英

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

I want to check if an element is present in the vector or not. I searched for answers and I found this

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

What if the vector is of type structure. Can we still use this to find if there is match in the vector. I want to find in the vector using the field id in the struct entry. Is it possible??

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

What you need is 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM