STL iterator

A

Allerdyce.John

Hi,

I am reading c++ primer, in the section about iteraor, it has an
example:

To iterate over the elements of any container type, we write
for (iter = container.begin(); iter != container.end(); ++iter)
do_soemthing_wtih_element (*iter);

why we write "++iter" instead of "iter++"?
 
V

Victor Bazarov

I am reading c++ primer, in the section about iteraor, it has an
example:

To iterate over the elements of any container type, we write
for (iter = container.begin(); iter != container.end(); ++iter)
do_soemthing_wtih_element (*iter);

why we write "++iter" instead of "iter++"?

This is covered in the FAQ, I believe. See section 13.
http://www.parashift.com/c++-faq-lite/

V
 
M

Mike Wahler

Hi,

I am reading c++ primer, in the section about iteraor, it has an
example:

To iterate over the elements of any container type, we write
for (iter = container.begin(); iter != container.end(); ++iter)
do_soemthing_wtih_element (*iter);

why we write "++iter" instead of "iter++"?

It will give a compiler a better chance of creating
efficient code. See FAQ for details:
http://www.parashift.com/c++-faq-lite/

Your question is answered in section 13 (But
be sure to read the whole FAQ, it contains
much useful information.)

-Mike
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

To iterate over the elements of any container type, we write
for (iter = container.begin(); iter != container.end(); ++iter)
do_soemthing_wtih_element (*iter);

why we write "++iter" instead of "iter++"?

The FAQ covers the efficiency aspect; but to me the reason is simpler than
that: because we want to point to the next element, nothing else...

Prefix increment, just increments; and in the case of iterators,
incrementing is pointing to the next element.

On the other hand; postfix increment stores the old state of the object,
increments the object, and returns the stored old state.

Since the for loop above only deals only with incrementing, the author of
the code uses prefix increment.

Ali
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top