std::find() on a vector of pointers

2019-07-15 04:29发布

问题:

I want to search through a vector of pointers to and compare the pointers to an int. My initial idea was to use std::find() but i realized that I cannot compare a pointer to an int.

Example:

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

myvector is a vector containing pointers to a class object, i.e., vector<MyClass*> myvector.MyClass contains a method getValue() which will return an integer value and I basically want to go through the vector and check each object's getValue() return value to determine what i do.

Using the previous example:

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
}

Its almost like an absolute condition where if any pointer's value in my vector is a 0, i output zero, i output 0. If no zero is found, i look to see if there is a 1. If 1 is found, i output 1. Etc, etc..

回答1:

Use std::find_if() instead. The other answers show how to use a lambda for the predicate, but that only works in C++11 and later. If you are using an earlier C++ version, you can do this instead:

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()
{
    //...
}


回答2:

What you want is std::find_if and a custom compare function/functor/lambda. With the custom comparator you can call the correct function to do the comparison. Something like

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


回答3:

You need to tell the compiler that you want to call getValue() on each pointer, and that's the thing you're searching for. std::find() is only for matching values, for anything more complicated, there's std::find_if:

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


回答4:

You can use std::find_if which relies on a predicate rather than a value

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