Re: Searching in sorted containers
????????????????????? ?????????????????????????????????????? wrote:
Hello all,
suppose we have the following class:
class A {
public:
const string& getName() const;
bool operator<(const A& rhs) const {
return getName() < rhs.getName();
}
/* more fields and methods here */
};
and that we have a container sorted on the value of the getName() method.
How can one search for the item with a given value of the getName()
method knowing that algorithms like std::lower_bound wouldn't accept a
string as a search item?
I need to write something like:
std::vector<A> v;
/* Fill v */
std::sort(v.begin(), v.end());
std::lower_bound(v.begin(), v.end(), /* want to put a string here */));
The easiest solution would be to overload the < (less than) operator
with a std::string and a class A object as its operands:
bool operator<(const A& lhs, const std::string& rhs)
{
return lhs.getName() < rhs;
}
bool operator<(const std::string& lhs, const A& rhs)
{
return lhs < rhs.getName();
}
int main()
{
std::vector<A> v;
/* Fill v */
std::sort(v.begin(), v.end());
// "search" converts to a std::string...
std::lower_bound(v.begin(), v.end(), "search");
}
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]