473,473 Members | 1,854 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Good practice? modifying vector while iterating through it

I was wondering whether it is good programming practice or asking
for trouble to modify a vector while iterating through it. That is, I
want to do something like the following pseudocode in C++:

for each element of the vector
for each subsequent element of the vector
if the belong together <some code to compare them>
then merge the elements (add the 2nd to the 1st, then
delete the 1st)

Does deleting an element before reaching it in the iteration mess up
the indexing and/or size of the vector, or do C++ compilers handle
this fine?

Thanks, Alan

Feb 16 '07 #1
5 12039
Alan wrote:
I was wondering whether it is good programming practice or asking
for trouble to modify a vector while iterating through it.
Both :-)

a) It is a little more complicated than just iterating through a vector.
b) Sometimes, it is just what you need to do.
That is, I
want to do something like the following pseudocode in C++:

for each element of the vector
for each subsequent element of the vector
if the belong together <some code to compare them>
then merge the elements (add the 2nd to the 1st, then
delete the 1st)
Do you mean delete the 2nd?
Does deleting an element before reaching it in the iteration mess up
the indexing and/or size of the vector, or do C++ compilers handle
this fine?
a) Deleting any element will change the size of the vector. Also the return
value of end() will change. The indexing will still run from 0 to size()-1
and the relative order of elements will not change. In that sense, C++
handles deletions within a vector (and indeed within any container) just
fine.
b) Calling erase on a vector invalidates all iterators, pointers, and
references to elements at and _behind_ the point of deletion. In
particular: if you really want to erase the lower-index element, you are in
trouble using iterators.

In any case, you will invalidate the inner iterator in your nested loop.
Thus, you will have to take special care. An idiom for erasing an element
within a loop for sequences is:

for ( sequence<int>::iterator iter = some_start_value;
iter != the_seq.end(); ) { // note the missing ++iter !
// do something
if ( we_do_not_erase ) {
++iter;
} else {
iter = the_seq.erase( iter );
}
}

It might be better to just use a running index and not an iterator. In this
case you have to keep in mind that you do not need to increment the index
when deleting the element (since the following element moves down).
c) On the other hand, erasing elements in the middle of a vector is costly
since all subsequent elements move. You might want to consider std::list<>
instead of std::vector. In this case, you will have to use iterators.

Best

Kai-Uwe Bux

Feb 16 '07 #2
Do you mean delete the 2nd? Oops, yes I did.

Thank you for your advice. Alan

Feb 16 '07 #3
"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:er**********@murdoch.acc.Virginia.EDU...
c) On the other hand, erasing elements in the middle of a vector is costly
since all subsequent elements move. You might want to consider std::list<>
instead of std::vector. In this case, you will have to use iterators.
Alternatively, instead of deleting elements from the vector, create a new
vector with just the elements that you want to keep. This technique avoids
the complexity and time overhead of deleting elements from the middle of the
vector, and the space overhead of using a list. It does create two copies
of the elements you keep, but that might be less than the space overhead for
a list, depending on how large the elements are.
Feb 16 '07 #4
Andrew,
Good idea. Thanks
Feb 16 '07 #5

Andrew Koenig wrote:
>
>c) On the other hand, erasing elements in the middle of a vector is
costly
since all subsequent elements move. You might want to consider
std::list<>
instead of std::vector. In this case, you will have to use iterators.

Alternatively, instead of deleting elements from the vector, create a new
vector with just the elements that you want to keep. This technique
avoids the complexity and time overhead of deleting elements from the
middle of the vector, and the space overhead of using a list. It does
create two copies of the elements you keep, but that might be less than
the space overhead for a list, depending on how large the elements are.
One can say concrete rules to compare list and vector. List adds size of one
or two pointers (assuming worst - two) in addition to size of type of its
object (for each object).

Feb 19 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: David Jones | last post by:
Hi I have a list of values stored in a vector e.g. std::vector<int> x; x = 1; x = 4; x = 2; x = 4;
14
by: Jim West | last post by:
I'm curious why I might be getting such a large performance difference between using a map iterator and a vector iterator. This is a computational electromagnetics code where I have to separate...
11
by: Jason Heyes | last post by:
Look at my code: void modify_element(BigType &x) { /* not shown */ } BigType modify_element_copy(BigType x) { modify_element(x);
10
by: LP | last post by:
Hi, I was asked at the tech screening what the linked list was which I answered with "academic" definition. Then a guy asked me how I would implement a linked list in C# and what would be a good...
24
by: Gaijinco | last post by:
I found one of that problems all of us have solve when they begin programming: given 3 numbers print the greater and the lesser one of the set. I was trying to remember the if-then-else...
2
by: zl2k | last post by:
hi, all I need to use gsl_vector pointer with std::vector but not sure how to free the memory when I don't need it. Here is a piece of the code. =================== std::vector<gsl_vector *...
3
by: =?iso-8859-1?q?Erik_Wikstr=F6m?= | last post by:
I have some code where there's this vector of pointers to objects and I need to delete and erase some of them, the problem is that to know which I need to iterate through the vector and I'm trying...
2
by: Christopher | last post by:
Seems odd, but I was wondering if I am in the middle of iterating through a vector, is there a way to calc which index I am currently on? something like: it - vec.begin()? I don't want to change...
13
by: prasadmpatil | last post by:
I am new STL programming. I have a query regarding vectors. If I am iterating over a vector using a iterator, but do some operations that modify the size of the vector. Will the iterator recognize...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.