Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

class boundary
{
     public:
     int get_id();
}

std::vector<boundary> sample;

Now I need to find the boundary object ,which's int id generated by get_id() is same as the int value I'm searching.

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 do I achieve this?

like image 438
hisham Avatar asked Mar 01 '17 06:03

hisham


2 Answers

You should use std::lower_bound in this case:

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

(replace function pointer with function object if you want better performance)

like image 113
Laney Avatar answered Oct 19 '22 10:10

Laney


Assumption: you want to obtain a reference to the sought element (rather than an iterator to it).

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

Now, you can use it:

boundary& b = find_boundary(sample, 5);
like image 37
Andrzej Avatar answered Oct 19 '22 10:10

Andrzej