std::find() 在指针向量上

std::find() on a vector of pointers

我想搜索一个指针向量并将这些指针与 int 进行比较。我最初的想法是使用 std::find() 但我意识到我无法将指针与 int.

进行比较

示例:

if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
   //do something
}

myvector 是一个向量,包含指向 class 对象的指针,即 vector<MyClass*> myvectorMyClass 包含一个方法 getValue(),它将 return 一个整数值,我基本上想遍历向量并检查每个对象的 getValue() return 值以确定我做什么。

使用前面的例子:

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,它依赖于谓词而不是值

if(std::find_if(myvector.begin(), myvector.end(), [](MyClass* my) { return my->getValue() == 0; }) != myvector.end()
{
   //Output 0
}

您想要的是 std::find_if 和自定义比较 function/functor/lambda。使用自定义比较器,您可以调用正确的函数来进行比较。像

std::find_if(myvector.begin(), myvector.end(), [](MyClass* e) { return e->getValue() == 0; })

你需要告诉编译器你想在每个指针上调用 getValue(),这就是你要搜索的东西。 std::find() 仅用于匹配值,对于更复杂的值,有 std::find_if:

std::find_if(myvector.begin(), myvector.end(),
    [](const MyClass* c) { return c->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()
{
    //...
}