stl::find_if 与用户搜索

发布于 2024-08-06 02:49:57 字数 247 浏览 1 评论 0原文

我想知道是否有一种方法可以使用 stl::find_if 来搜索用户输入的值,

我不知道如何在不使用任何不良约定(全局)或添加扩展代码负载的情况下做到这一点。

例如,如果用户输入 10 的 int x,那么我想搜索一个整数向量

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜灵血窟げ 2024-08-13 02:49:57

您可以使用equal_to

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

You can use equal_to:

find_if(a.begin(), a.end(), bind2nd(equal_to<int>(), your_value));
冬天的雪花 2024-08-13 02:49:57

pred 必须是具有重载 () 运算符的类型的实例,因此可以像函数一样调用它。

struct MyPred
{
    int x;

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

(为了简洁起见,这里使用 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);

编写这样的自定义类(带有“大量”代码!)至少可以说很麻烦,但在 C++0x 中使用 lambda 语法时会得到很大改进已添加。

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.

梦萦几度 2024-08-13 02:49:57

您可以使用 boost::bind 来获得更通用的解决方案,例如:

struct Point
{
 int x;
 int y;
};


vector< Point > items;

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

将找到一个 x 等于 xValue 的点

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文