 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Albert Jin Guest
|
Posted: Thu Jun 08, 2006 3:29 am Post subject: How to get the iterator for a value less than the key specif |
|
|
Neither of the two methods, lower_bound and upper_bound, for std::set
does return the iterator less than the key specified. Is there a
better way to approach this?
template <typename Set>
typename Set::const_reverse_iterator less_lower_bound(Set const & set,
typename Set::const_reference key) {
Set::key_compare key_comp = set.key_comp();
Set::const_reverse_iterator i = set.rbegin();
for (; i != set.rend(); ++i) {
if (!key_comp(key, *i)) {
break;
}
}
return i;
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
Eric Johnson Guest
|
Posted: Fri Jun 09, 2006 9:10 am Post subject: Re: How to get the iterator for a value less than the key sp |
|
|
Albert Jin wrote:
| Quote: | Neither of the two methods, lower_bound and upper_bound, for std::set
does return the iterator less than the key specified. Is there a
better way to approach this?
|
Hi Albert,
The problem I see with your approach is that it performs a linear
search, so it will tend to be slow on large data sets. What I have
done is to just use lower_bound and then decrement the iterator. You
do have to check against begin() before decrementing the iterator, but
it should be faster than your approach.
Something like this:
typedef std::set<SomeClass> ClassSet;
.. . .
ClassSet MySet;
.. . .
SomeClass Obj;
.. . .
ClassPtrSet::iterator iter = MySet.lower_bound(Obj);
if ( iter != MySet.begin() )
{
--iter;
}
// at this point the iterator should be "pointing" to the value less
than the key specified.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ] |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|