Noo*_*eer 4 c++ pointers vector find
我想通过指针向量搜索并比较指向的指针int.我最初的想法是使用std::find()但我意识到我无法比较指针int.
例:
if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
//do something
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
它几乎像一个绝对条件,如果我的向量中的任何指针值是0,我输出零,我输出0.如果没有找到零,我看看是否有1.如果找到1,我输出1等等.
你想要的是std::find_if一个自定义比较函数/ functor/lambda.使用自定义比较器,您可以调用正确的函数进行比较.就像是
std::find_if(myvector.begin(), myvector.end(), [](MyClass* e) { return e->getValue() == 0; })
Run Code Online (Sandbox Code Playgroud)
请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()
{
//...
}
Run Code Online (Sandbox Code Playgroud)