Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::find() on a vector of pointers

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..

like image 374
Noobgineer Avatar asked Feb 18 '16 19:02

Noobgineer


2 Answers

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()
{
    //...
}
like image 101
Remy Lebeau Avatar answered Sep 20 '22 18:09

Remy Lebeau


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; })
like image 44
NathanOliver Avatar answered Sep 17 '22 18:09

NathanOliver