# STL list/map - rest size

Discussion in 'C++' started by Thomas Kowalski, Aug 17, 2006.

1. ### Thomas KowalskiGuest

Hi everyone,
I would like if there is an easy way to get the number of elements left
after an given iterator?
I have an interator called it somethere between beginning and end of an
list / map and want to know how often I have to call ++it before I
arrive at the end of the list. Means how many elements are left after
the given iterator it. My first solution (see below) is quite
inefficent.

int restsize()
{
int i=0;
T::iterator it2 = it;
for ( ;it2 != somelistormap.end(); ++it2)
{
++i;
}
return i;
}

Thomas Kowalski, Aug 17, 2006

2. ### Victor BazarovGuest

Thomas Kowalski wrote:
> I would like if there is an easy way to get the number of elements
> left after an given iterator?

Why? What are you trying to accomplish by that?

> I have an interator called it somethere between beginning and end of
> an list / map and want to know how often I have to call ++it before I
> arrive at the end of the list. Means how many elements are left after
> the given iterator it. My first solution (see below) is quite
> inefficent.
>
> int restsize()
> {
> int i=0;
> T::iterator it2 = it;
> for ( ;it2 != somelistormap.end(); ++it2)
> {
> ++i;
> }
> return i;
> }

You can take the last element and then see 'std::distance', but it will
most likely do the same increment, since std::map iterators are not of
the random-access kind.

V
--

Victor Bazarov, Aug 17, 2006

3. ### Thomas KowalskiGuest

Hi Victor,

> Why? What are you trying to accomplish by that?

Need it to set the size of the return datastructure X. X is specified
stupidly.

> You can take the last element and then see 'std::distance', but it will
> most likely do the same increment, since std::map iterators are not of
> the random-access kind.

At least its a cleaner Thanks.

Regards,
Thomas Kowalski

Thomas Kowalski, Aug 17, 2006