如何通过结构中的变量确定结构是否存在于结构向量中
How to find out if a struct is present in a vector of structs by a variable within the struct
我想检查矢量中是否存在某个元素。我搜索了答案并找到了这个
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();
我想检查矢量中是否存在某个元素。我搜索了答案并找到了这个
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();