Skip to content

Std container iteration

panzergame edited this page Dec 26, 2016 · 2 revisions

Since the support of C++11, the loop are allowed to use the following syntax:

for (Type item : container) {

}

Else it we need to access to the iterator for copy, insert on other containers. All std container iteration which not modify the container and doesn't request the index should be write:

for (std::container<Type>::iterator it = container.begin(), end = container.end(); it != end; ++it) {

}

Where end is defined at the beginning to avoid calling container.end() for every iteration.

If the iteration may remove elements of the container and the container is an std::map, the loop will be:

for (std::container<Type>::iterator it = container.begin(), end = container.end(); it != end;) {
    if (conditionToRemove) {
        container.erase(it++);
    else {
        ++it;
    }
}

If the container is an std::vector (or any derived types), the loop is:

for (std::container<Type>::iterator it = container.begin(); it != container.end();) {
    if (conditionToRemove) {
        it = container.erase(it);
    else {
        ++it;
    }
}

Contrary to before end MUST be not defined at the beginning as constant, because some container can be reallocated when erasing an element.

Assigning it with the returned value of erase is to prevent the reallocation of the container when removing a element.

Clone this wiki locally