Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

help on std::iterator_traits?

17 views
Skip to first unread message

Jess

unread,
Jun 28, 2007, 10:30:55 AM6/28/07
to
Hello,

I read a document that says iterator_traits is contains only nested
definitions. It seems to have definitions like value_type, reference
etc. If I define my own container, I can define these types without
iterator_traits. Therefore, could somebody please tell me why we need
to use iterator_traits at all?

Thanks a lot!
Jess

Victor Bazarov

unread,
Jun 28, 2007, 10:55:30 AM6/28/07
to

You don't.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


Kai-Uwe Bux

unread,
Jun 28, 2007, 10:58:05 AM6/28/07
to
Jess wrote:

> Hello,
>
> I read a document that says iterator_traits is contains only nested
> definitions. It seems to have definitions like value_type, reference
> etc. If I define my own container,

You probably mean "iterator" instead of "container"

> I can define these types without
> iterator_traits. Therefore, could somebody please tell me why we need
> to use iterator_traits at all?

The iterator_traits are the interface for algorithms to know about the
iterators passed. Note that T* is supposed to be a valid iterator. Yet,
there is no such thing as (T*)::value_type. However, iterator_traits<T*> is
specialized in the expected way. This is another case of a problem being
solved by introducing "yet another level of indirection"(tm).


Best

Kai-Uwe Bux

Zeppe

unread,
Jun 28, 2007, 11:01:12 AM6/28/07
to

Because the algorithms that rely on the iterators don't really care
about your container. If you write a container, and write your own
iterator for it, an algorithm that performs some operation on your data
can be written as:

template <class It>
void foo(It begin, It end){
iterator_traits<It>::value_type v;
// bla bla bla...
}

it's an elegant way to group all the information that depends on the
iterator.

Regards,

Zeppe

0 new messages