Re: Searching in sorted containers
In article <448b045c$0$27289$626a54ce@news.free.fr>, ????? ?????????
<ivan.bogouchev@gmail.com> 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 */));
Thanks in advance
since A is ordered by the member function getName(). The simplest
solution without further information on class A is to use
boost::transform_iterator. Something like:
std::vector<A>::iterator = std::lower_bound
(
boost::make_transform_iterator(v.begin(),
std::mem_fun_ref(&A::getName));
boost::make_transform_iterator(v.end(),
std::mem_fun_ref(&A::getName)),
the_string
).base();
comes to mind. The boost::make_transform_iterator's above create
a random access iterator whose value_type is std::string and iterates
through the vector. The created iterator has a member function base
which converts the created iterator back to the original iterator.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]