Binary_search to find a class object using the return variable of its member function [C ++]

I have a vector of class objects sorted by its integer indices. But the object index is generated by a member function of the class - therefore no is int idstored as a member variable.

class boundary
{
     public:
     int get_id();
}

std::vector<boundary> sample;

Now I need to find the object boundarythat int id, generated get_id(), is the same as the int valueone I'm looking for.

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

Is it possible to use binary_search in this case? How to achieve this?

+4
source share
3 answers

In this case, you should use 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);

( , )

+5

: ( ).

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

You can create an object that meets the concept of Compare. http://en.cppreference.com/w/cpp/concept/Compare

For instance:

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

Source: https://habr.com/ru/post/1671103/


All Articles