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?
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.
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.
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.
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.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With