confusion with insert iterator

W

wenmang

Hi, all:
I am reading the book "The C++ Stadnard Library" by Josuttis. I have
trouble to understand
operations for the insert iterator(page 272).
++itr, *itr and itr++ are defined as no-op, and "itr = value"(supported
expression *itr = value") is
defined as "inserts value"
The example given in the book is:
vector<int> coll;
back_insert_iterator<vector<int> > itr(coll);
....
*itr = 1;
itr++;
*itr = 2;
*itr++;
....
Here is my question, if "itr++" defined as no-op what is the purpose of
using itr++ in the above
example? why could we use just:
*itr = 1;
*itr = 2;
instead?


Thanks.
 
P

Pete Becker

Here is my question, if "itr++" defined as no-op what is the purpose of
using itr++ in the above
example? why could we use just:
*itr = 1;
*itr = 2;
instead?

You could, but that shortened code won't work right with other kinds of
iterators. If you're writing a general-purpose algorithm you need to
work with all writable iterators, and that means you have to increment
the iterator.
 
R

Rolf Magnus

Hi, all:
I am reading the book "The C++ Stadnard Library" by Josuttis. I have
trouble to understand
operations for the insert iterator(page 272).
++itr, *itr and itr++ are defined as no-op, and "itr = value"(supported
expression *itr = value") is
defined as "inserts value"
The example given in the book is:
vector<int> coll;
back_insert_iterator<vector<int> > itr(coll);
...
*itr = 1;
itr++;
*itr = 2;
*itr++;
...
Here is my question, if "itr++" defined as no-op what is the purpose of
using itr++ in the above example? why could we use just:
*itr = 1;
*itr = 2;
instead?

That would only work with an insert iterator. If you include the operator++
call, you can later exchange the iterator with a forward iterator, and the
code will still work.
In the case of templates, the above might be part of one that doesn't even
know which type of iterator to expect. Think of std::copy. It will do
something similar to:

while (itr1 != end)
{
*itr2 = *itr1;
++itr1;
++itr2;
}

And when you use std::copy with an insert iterator for itr2, it will still
do the increment, since it doesn't care what type of iterator you give it.
 

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,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top