Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the common misuse of using STL containers with iterators? [closed]

Tags:

c++

iterator

stl

What are the common misuse of using STL containers with iterators?

like image 667
yesraaj Avatar asked Feb 03 '09 12:02

yesraaj


People also ask

What are the STL iterators and what is their purpose?

Iterators are used to point at the memory addresses of STL containers. They are primarily used in sequences of numbers, characters etc. They reduce the complexity and execution time of the program.

What is the use of iterate over container in STL?

Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of an iterator is a pointer. A pointer can point to elements in an array and can iterate through them using the increment operator (++).


2 Answers

Forgetting that iterators are quite often invalidated if you change the container by inserting or erasing container members.

For many great tips on using STL I highly recommend Scott Meyers's book "Effective STL" (sanitised Amazon link)

like image 142
Rob Wells Avatar answered Oct 05 '22 22:10

Rob Wells


The end range check should be using != and not < since the order of the pointers isn't guaranteed.

Example:

for(it = list.begin(); it != list.end(); ++it)
{
     // do stuff
}
like image 45
Mats Fredriksson Avatar answered Oct 05 '22 22:10

Mats Fredriksson