Martin Drozdik
Martin Drozdik

Reputation: 13313

Are iterators valid after sorting or removing elements? Is this code a ticking time bomb?

I just wanted to ask if iterators are valid after sorting or removal of elements. When we insert into a container, it can be reallocated to find more space and invalidate existing iterators. But what happens with sorting and removal of elements? Can those force the container to be reallocated?

Is this code going to crash once?

QVector<Foo> container;

b = container.begin();
e = container.end();

while (container.count() > newCount)
{
    computeSomePropertyOfFoo(b, e);  // Computes property between b and e
    sortByThatProperty(b, e);        // sorts members between b and e
    container.erase(--e);
}

Upvotes: 2

Views: 798

Answers (1)

Mat
Mat

Reputation: 206699

From the Container Classes documentation:

The Iterator Classes

Iterators provide a uniform means to access items in a container. Qt's container classes provide two types of iterators: Java-style iterators and STL-style iterators. Iterators of both types are invalidated when the data in the container is modified or detached from implicitly shared copies due to a call to a non-const member function.

So yes, your code is incorrect. You shouldn't "cache" the iterators the way you do it.

Upvotes: 6

Related Questions