[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

Hot to get iterator to specific map key?

Steve555

12/16/2008 10:42:00 AM

I have a map with integer keys.

How do I loop through with an iterator so that I start with an iter
that corresponds to a key >= x?
(i.e. in the loop I only want to operate on elements with a key >= x)

myMapType::iterator iter, startIter = iter starting with x ???;
for(iter = startIter; iter != myMap.end(); ++iter)
{
....
}

Is this possible or do I just have to start from myMap.begin() and
check each key?
I can't use advance() as the keys aren't contiguous

Thanks
Steve
2 Answers

Leandro Melo

12/16/2008 11:04:00 AM

0

On 16 dez, 08:42, Steve555 <foursh...@btinternet.com> wrote:
> I have a map with integer keys.
>
> How do I loop through with an iterator so that I start with an iter
> that corresponds to a key >= x?
> (i.e. in the loop I only want to operate on elements with a key >= x)
>
> myMapType::iterator iter,   startIter = iter starting with x ???;
> for(iter = startIter; iter != myMap.end(); ++iter)
> {
> ...
>
> }
>
> Is this possible or do I just have to start from myMap.begin() and
> check each key?
> I can't use advance() as the keys aren't contiguous


The following would give you an iterator to the first element whose
key is not less than x. If no such element exists you'll get a past-
the-end iterator.

myMapType::iterator iter = myMap.lower_bound(x);


--
Leandro T. C. Melo

Steve555

12/16/2008 11:12:00 AM

0

On 16 Dec, 11:04, Leandro Melo <ltcm...@gmail.com> wrote:
> On 16 dez, 08:42, Steve555 <foursh...@btinternet.com> wrote:
>
>
>
> > I have a map with integer keys.
>
> > How do I loop through with an iterator so that I start with an iter
> > that corresponds to a key >= x?
> > (i.e. in the loop I only want to operate on elements with a key >= x)
>
> > myMapType::iterator iter,   startIter = iter starting with x ???;
> > for(iter = startIter; iter != myMap.end(); ++iter)
> > {
> > ...
>
> > }
>
> > Is this possible or do I just have to start from myMap.begin() and
> > check each key?
> > I can't use advance() as the keys aren't contiguous
>
> The following would give you an iterator to the first element whose
> key is not less than x. If no such element exists you'll get a past-
> the-end iterator.
>
> myMapType::iterator iter = myMap.lower_bound(x);
>
> --
> Leandro T. C. Melo

Thanks for the reply. Of course, classic case of not seeing the wood
for the trees.

Steve