Reputation: 37
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] = {};
};
Upvotes: 2
Views: 1424
Reputation: 9619
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();
Upvotes: 2