我想检查向量中是否存在元素。我搜索了答案,我找到了这个
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();