tags:

views:

275

answers:

3

I was wondering if there was a way to use the stl::find_if to search for a user inputted value

I don't know to do that without using any bad conventions(globals) or adding loads of extended code.

For example, if a user inputs a int x for 10, then I want to search an vector of ints

iterator = find_if(begin,end,pred) //but how does pred know the user inputted value?
+3  A: 

The pred must be an instance of a type that has the overloaded () operator, so it can be called like a function.

struct MyPred
{
    int x;

    bool operator()(int i)
    {
        return (i == x);
    }
};

(Using a struct for brevity here)

std::vector<int> v;

// fill v with ints

MyPred pred;
pred.x = 5;

std::vector<int>::iterator f 
     = std::find_if(v.begin(), 
                    v.end(), 
                    pred);

Writing custom classes like this (with "loads" of code!) is cumbersome to say the least, but will be improved a lot in C++0x when lambda syntax is added.

Daniel Earwicker
But how does the user set x?
Stanislav Palatnik
The programmer sets 'x' by assigning to it, as shown above. Are you asking about how to read input from the user? That's basically a totally different question.
Daniel Earwicker
Whoops yea :P. Thanks
Stanislav Palatnik
No problem - obviously it's better practice to make the data members private and provide a constructor to initialize them, I just made `x` public to make it shorter and hopefully clearer.
Daniel Earwicker
Using a ctor actually makes the code shorter:`...std::find_if(v.begin(), v.end(), pred(5));`Of course UncleBen's comment had the right answer -- when you just need to find a particular value, use std::find instead of find_if.
Jerry Coffin
+6  A: 

You can use equal_to:

find_if(a.begin(), a.end(), bind2nd(equal_to<int>(), your_value));
Greg Hewgill
thanks for the clean solution
Stanislav Palatnik
Ah.. bind2nd.. I love functional programming in C++ ;-)
Mads Elvheim
+3  A: 

You can use boost::bind, for more general solution, for example:

struct Point
{
 int x;
 int y;
};


vector< Point > items;

find_if( items.begin(), items.end(), boost::bind( &Point::x, _1 ) == xValue );

will find a point whose x equals xValue

Klesk