Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using find_if on a vector of object

Tags:

c++

vector

I have a vector of that looks like the following:

class Foo {     //whatever };  class MyClass {     int myInt;     vector<Foo> foo_v; }; 

And let's say, in the main:

int main (void) {     vector<MyClass> myClass_v; } 

I want to find a object in myClass_v that has myInt == bar. I don't care about foo_v. I thought of using the std::find_if function:

std::find_if(myClass_v.begin(),myClass_v.end(),condition); 

with

bool MyClass::condition(MyClass mc) {     if(mc.myInt==5)         return true;     else         return false; } 

However the compiler says that condition() is missing arguments. Could you tell me what am I doing wrong? I thought that std::find_if would call condition(*First), with First being a pointer to a myClass object.

Or is there another good way to do the same thing?

like image 727
gramm Avatar asked Jul 13 '11 12:07

gramm


People also ask

Should I use std for vector?

As a rule of thumb, you should use: a std::array if the size in fixed at compile time. a std::vector is the size is not fixed at compile time. a pointer on the address of their first element is you need low level access.

What does Find_if return?

C++ Algorithm find_if() function returns the value of the first element in the range for which the pred value is true otherwise the last element of the range is given.

What is std :: Find_if?

The C++ function std::algorithm::find_if() finds the first occurrence of the element that satisfies the condition. It uses unary predicate to specify condition.

How do you find the vector of an object?

Finding an element in vector using STL Algorithm std::find() Basically we need to iterate over all the elements of vector and check if given elements exists or not. This can be done in a single line using std::find i.e. std::vector<int>::iterator it = std::find(vecOfNums.


1 Answers

That's not how predicates work. You have to supply either a free function bool Comparator(const MyClass & m) { ... }, or build a function object, a class that overloads operator():

struct MyClassComp {   explicit MyClassComp(int i) n(i) { }   inline bool operator()(const MyClass & m) const { return m.myInt == n; } private:   int n; };  std::find_if(v.begin(), v.end(), MyClassComp(5)); 

In C++0x:

std::find_if(v.begin(), v.end(),              [](const MyClass & m) -> bool { return m.myInt == 5; }); 

This captureless lambda is in fact equivalent to a free function. Here is a capturing version that mimics the predicate object:

const int n = find_me(); std::find_if(v.begin(), v.end(),              [n](const MyClass & m) -> bool { return m.myInt == n; }); 
like image 146
Kerrek SB Avatar answered Oct 14 '22 21:10

Kerrek SB