[英]std::find() on a vector of pointers
我想搜索一个指针向量并比较指向int
的指针。 我最初的想法是使用std::find()
但我意识到我无法比较指向int
的指针。
例:
if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
//do something
}
myvector
是一个包含指向类对象的指针的向量,即vector<MyClass*> myvector
。 MyClass
包含一个方法getValue()
,它将返回一个整数值,我基本上想要通过向量并检查每个对象的getValue()
返回值来确定我做了什么。
使用前面的示例:
if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
//Output 0
}
else if(std::find(myvector.begin(), myvector.end(), 1) != myvector.end()
{
//Output 1
}
else if(std::find(myvector.begin(), myvector.end(), 2) != myvector.end()
{
//Output 2
}
它几乎像一个绝对条件,如果我的向量中的任何指针值是0,我输出零,我输出0.如果没有找到零,我看看是否有1.如果找到1,我输出1等等。
你想要的是std::find_if
和自定义比较函数/ functor / lambda。 使用自定义比较器,您可以调用正确的函数进行比较。 就像是
std::find_if(myvector.begin(), myvector.end(), [](MyClass* e) { return e->getValue() == 0; })
请改用std::find_if()
。 其他答案显示了如何将lambda用于谓词,但这只适用于C ++ 11及更高版本。 如果您使用的是早期的C ++版本,则可以执行以下操作:
struct isValue
{
int m_value;
isValue(int value) : m_value(value) {}
bool operator()(const MyClass *cls) const
{
return (cls->getValue() == m_value);
}
};
...
if (std::find_if(myvector.begin(), myvector.end(), isValue(0)) != myvector.end()
{
//...
}
您需要告诉编译器您要在每个指针上调用getValue()
,这就是您要搜索的内容。 std::find()
仅用于匹配值,对于更复杂的东西,有std::find_if
:
std::find_if(myvector.begin(), myvector.end(),
[](const MyClass* c) { return c->getValue() == 0; }
);
您可以使用std::find_if
,它依赖于谓词而不是值
if(std::find_if(myvector.begin(), myvector.end(), [](MyClass* my) { return my->getValue() == 0; }) != myvector.end()
{
//Output 0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.