开发者

stl::find_if with user search

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 开发者_Go百科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?


You can use equal_to:

find_if(a.begin(), a.end(), bind2nd(equal_to<int>(), your_value));


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜