简体   繁体   English

用户搜索stl :: find_if

[英]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 我想知道是否有办法使用stl :: find_if来搜索用户输入的值

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 例如,如果用户输入的int为10,那么我想搜索int的向量

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

你可以使用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. pred必须是具有overloaded()运算符的类型的实例,因此可以像函数一样调用它。

struct MyPred
{
    int x;

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

(Using a struct for brevity here) (在这里使用struct简洁)

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. 编写这样的自定义类(带有“加载”代码!)至少可以说很麻烦,但是当添加lambda语法时,C ++ 0x会有很多改进。

You can use boost::bind, for more general solution, for example: 您可以使用boost :: bind,以获得更通用的解决方案,例如:

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 会找到一个x等于xValue的点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM