C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

How to get the iterator for a value less than the key specif

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
Albert Jin
Guest





PostPosted: Thu Jun 08, 2006 3:29 am    Post subject: How to get the iterator for a value less than the key specif Reply with 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?

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





PostPosted: Fri Jun 09, 2006 9:10 am    Post subject: Re: How to get the iterator for a value less than the key sp Reply with quote



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
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Page 1 of 1

 
Jump to:  
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


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.