尝试在包含自定义对象的向量上使用std::find
但我不知道如何使用它来完成我要尝试做的事情。还有另一种做这种事情的方法吗?
struct object
{
char x;
int y;
object(char x, int y)
{
this->x = x;
this->y = y;
}
};
int main()
{
std::vector<object> vector;
object obj = object('X', 0);
vector.push_back(obj);
if (std::find(vector.begin(), vector.end(), ? ? ? ) != vector.end())
{
//do something
}
return 0;
}
我正在尝试找到obj.y
答案 0 :(得分:0)
std::find
算法具有多个版本,您可以定义其中的一些版本来比较元素。默认情况下,它将仅使用相等比较==
。
// v----- found is not a boolean, but an iterator
auto const found = std::find(vector.begin(), vector.end(), element_to_find);
如果相等还不够,则可以使用std::find_if
接受一个谓词来比较元素:
auto const predicate =
[&](auto const& element) {
return element.is_the_one(); // element.is_the_one() returns a boolean
// You can use obj.y here
};
// v----- found is not a boolean, but an iterator
auto const found = std::find_if(vector.begin(), vector.end(), predicate);
我建议阅读文档,以了解如何使用查找算法处理返回值。