Binary_search通过其成员函数的返回变量[C ]找到类对象

binary_search to find a class object by the return variable of its member function [c++]

本文关键字:变量 对象 返回 search 函数 成员 Binary      更新时间:2023-10-16

我有一个由整数索引排序的类对象的向量。但是对象的索引是由类的成员函数生成的 - 因此,没有int id作为成员变量存储。

class boundary
{
     public:
     int get_id();
}
std::vector<boundary> sample;

现在我需要找到boundary对象,get_id()生成的int id与我正在搜索的int value相同。

auto &iter = binary_search(sample.begin(),sample.end(), 5, custom_function)
 //should compare iter.get_id() == 5

在这种情况下,可以使用binary_search吗?我该如何实现?

在这种情况下,您应该使用std :: lower_bound:

bool custom_function(boundary& obj, int id)  { return obj.get_id() < id; }
...
auto iter = lower_bound(sample.begin(),sample.end(), 5, custom_function);

(如果需要更好的性能,将功能指针替换为功能对象)

假设:您想向寻求的元素获得参考(而不是迭代器)。

boundary& find_boundary(std::vector<boundary>& sample, int id)
// precondition: a boundary with id does exist in the sample
{ 
  auto less_by_id = [](boundary const& b, int id) // lambda is faster than function pointers
    { return b.get_id() < id; };
  auto it = lower_bound(sample.begin(), sample.end(), id, less_by_id);
  assert (it != sample.end());
  assert (it->get_id() == id);
  return *it;      
}

现在,您可以使用它:

boundary& b = find_boundary(sample, 5);

您可以创建满足"比较"概念的对象。http://en.cppreference.com/w/cpp/concept/compare

例如:

class Compare {
public:
    bool operator()(boundry a, boundry b) {
        return a.get_id() < b.get_id();
    }
}