【问题标题】:binary_search to find a class object by the return variable of its member function [c++]binary_search 通过其成员函数的返回变量来查找类对象[c++]
【发布时间】:2017-03-01 06:08:58
【问题描述】:

我有一个按其整数索引排序的类对象向量。但是对象的索引是由类的成员函数生成的——所以没有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 吗?我如何做到这一点?

【问题讨论】:

  • 如果 id 是由 get_id 函数生成的,并且没有将其存储在字段中,那么我很确定当所有对象调用在任何一种情况下,二分查找都是不切实际的。
  • 请记住样本(向量)可能不包含您要查找的对象。在这种情况下,你希望你的函数返回什么?
  • @Andrzej,我正在搜索的对象应该在向量中。我必须断言它

标签: c++ algorithm stl binary-search


【解决方案1】:

在这种情况下你应该使用 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);

(如果你想要更好的性能,用函数对象替换函数指针)

【讨论】:

    【解决方案2】:

    假设:您想要获得对所寻找元素的引用(而不是对其的迭代器)。

    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);
    

    【讨论】:

      【解决方案3】:

      您可以创建一个满足“比较”概念的对象。 http://en.cppreference.com/w/cpp/concept/Compare

      例如:

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

      【讨论】:

      • 虽然这并不能回答问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多