使用lower_bound,upper_bound和binary_search查找具有相等成员字段的对象

gsi*_*011 5 c++ search stl

我有一个看起来像这样的结构

struct Foo {
    int a;
};
Run Code Online (Sandbox Code Playgroud)

我有这些结构的向量,看起来像这样,

vector<Foo> foos;
Run Code Online (Sandbox Code Playgroud)

使用STL sort()函数,所有Foos都按整数a升序排序。现在,我想获取Foo成员字段a小于或等于给定数字的对象,例如STL lower_bound()函数。问题是STL lower_bound函数声明看起来像这样:

template <class ForwardIterator, class T, class Compare>
  ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator last,
                                const T& value, Compare comp );
Run Code Online (Sandbox Code Playgroud)

所以当我想做类似的事情时,

lower_bound(foos.begin(), foos.end(), 5, custom_comp);
Run Code Online (Sandbox Code Playgroud)

我不能,因为我要查找的int(在这种情况下为5)不是type Foo。我在Lower_bound(),upper_bound()和binary_search()中遇到此问题。custom_comp仅定义顺序,而没有定义a = 5的对象实际上等于int 5。

使用STL有什么优雅的方法吗?

编辑:

我意识到我的例子并不能完全代表我的问题。我实际上拥有的是Foo包含两个整数a和b。当我调用lower_bound时,我无权访问b(因为我不在乎)。现在,billz答案的问题是,我必须定义一个仅以a参数为参数的构造函数,在我看来,这不是很优雅(因为b未被定义或是任意的,并且该构造函数可以在码)。但是,如果这是唯一的选择,我会接受。

bil*_*llz 2

您可以为 struct Foo 提供一个构造函数

struct Foo {
  Foo(int x):a(x){
  }
    int a;
};
Run Code Online (Sandbox Code Playgroud)

您现在可以致电:

std::lower_bound(foos.begin(), foos.end(), 5, custom_comp);
Run Code Online (Sandbox Code Playgroud)

或者

std::lower_bound(foos.begin(), foos.end(), Foo(5), custom_comp);
Run Code Online (Sandbox Code Playgroud)

或者

Foo f(5);
std::lower_bound(foos.begin(), foos.end(), f, custom_comp);
Run Code Online (Sandbox Code Playgroud)

建议的方式是:

struct Foo {
  explicit Foo(int x):a(x){
  }
    int a;
};

std::lower_bound(foos.begin(), foos.end(), Foo(5), custom_comp);
Run Code Online (Sandbox Code Playgroud)