nutter
nutter

Reputation: 35

Finding a on object in a vector by one of its values

The problem I encountered and am unable to solve goes something like this. I have two classes:

class1
{
private:
  int identifier;
  double value;
public:
  setters,getters,etc...
}
class2
{
private:
  vector<class1> objects;
  vector<int> some_value;
  vector<double> other_value;
...
}

The problem is I need to search through the vector of objects in an object of the second class by its identifier in the class1 object(from a member function of class2). I tried something like:

int getObj(const int &ident, double &returnedValue, double &returnedOther_value)
{
  int p;
  p = find(objects.begin()->getIdentifier(),objects.end()->getIdentifier(),ident);
  ..

.. and then i was hoping to find a way to return from the found iterator values of corresponding(non-const) member variables value and other_value from both classes, but the code so far does not compile, because I'm likely doing the search all wrong. Is there a way I could do this with the find(or any other algorithm) or should I stick to my previous working realization with no algorithms?

Upvotes: 1

Views: 1153

Answers (1)

MikMik
MikMik

Reputation: 3466

You need to use find_if with a custom predicate. Something like:

class HasIdentifier:public unary_function<class1, bool>  
{  
public:
    HasIdentifier(int id) : m_id(id) { }  
    bool operator()(const class1& c)const  
    {  
        return (c.getIdentifier() == m_id);  
    }  
private:
    int m_id;  
};  


// Then, to find it:
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(ident));  

I haven't tested it, so maybe it needs some tweaking.

If you have C11, I guess you can use lambdas, but I don't have it, so I haven't had the chance to learn them.

UPDATE: I've added an example in http://ideone.com/D1DWU

Upvotes: 1

Related Questions