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?
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With