help on std::iterator_traits?

J

Jess

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
 
V

Victor Bazarov

Jess said:
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?

You don't.

V
 
K

Kai-Uwe Bux

Jess said:
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
 
Z

Zeppe

Jess said:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top