Re: Append Iterator
Jason Hise wrote:
On Oct 28, 11:18 am, "Timo Geusch" <t...@unixconsult.co.uk> wrote:
Jason Hise wrote:
I want to be able to store multiple copies
of iterators at different locations in the sequence, and I want them
to not be invalidated if a push_back occurs. To my knowledge, a
back_insert_iterator does not support this.
I may be missing the blindingly obvious here but isn't invalidating the
iterators a function of the container, not the iterator itself?
It is a function of the chosen container, which I think is my problem.
I want to solve the problem of building a container and remembering how
to access elements as I add them without locking myself into using a
specific container, and because of this invalidation I don't know that
it is possible. If I use a vector I need to remember indicees, and if
I use a list I need to remember iterators. If vector used an iterator
type that used indicees instead of raw pointers then it could offer the
guarantee that push_back would not invalidate existing iterators,
unifying the containers in this regard and making the append_iterator
possible.
A std::vector iterator does not have to be implemented as a pointer -
an implementation could declare an iterator class that uses an index
and a base address to iterate through the container's elements. But an
index-based iterator would be just as likely to be invalidated in this
situation as the pointer--based iterator. The problem is that the
vector may need to increase its allocated storage in order to
accomodate the new elements. Increasing the container's memory
allocation may necessitate moving its storage to a new address. In that
event, the base address of the indexing iterator (and not its index)
becomes invalid.
Of course a program can prevent push_back(), insert() or any kind of
inserting iterator from invalidating a container's iterators by
reserving adequate space for the elements to be added upfront:
std::vector<int> v;
v.reserve(3);
v.push_back(4);
vector::iterator temp = v.insert(v.end(), 5);
v.push_back(6);
*temp = 3;
*++temp = 2;
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]