问题
I am trying to refactor some code that doesn't use the STL to use the generic algorithms it provide. I have a struct like this :
struct A {
int i;
//other stuff...
};
// ...
A* array; // array of A objects, sorted by A::i member
int n = ...; // array size
there is then a function that was coded that takes A
, n
and an integer k
, whose purpose is to give me pointers to to the first and the last element of the array that have their i
member equal to k
.
This is implemented by hand in terms of binary search. I was thinking about using std::equal_range
. The problem is that it requires an object of type A to work, and it forces me to introduce a "dummy" A object with it's i
member equal to k
.
Is there a way to do this using the STL, without having to introduce a "dummy" object? thanks
回答1:
Provided your range is sorted according to the value of A::i
, this is trivially done with a custom comparator, but note that the comparator must be able compare both ways:
struct AComp
{
bool operator()(int n, A const & a) const { return n < a.i; }
bool operator()(A const & a, int n) const { return a.i < n; }
};
auto p = std::equal_range(array, array + n, 5, AComp());
Now the range [p.first, p.second)
contains the elements with A::i
equal to 5
.
The linked page contains more or less exactly this example.
回答2:
You may also use std::binary_search()
defined in <algorithm>
for binary search generally. The prorotype is:
template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val);
or:
template <class ForwardIterator, class T, class Compare>
bool binary_search (ForwardIterator first, ForwardIterator last,
const T& val, Compare comp);
回答3:
You can define a conversion operator(This is more like a hack, I guess)
class A
{
private:
int i;
public:
A(int x) : i(x){}
operator int(){
return i;
}
};
If this is done you dont have to define operator< in your struct.
来源:https://stackoverflow.com/questions/18749844/can-i-do-this-binary-search-using-the-stl