Aviv Cohn
Aviv Cohn

Reputation: 17243

Are iterators guaranteed to mutate when incrementing and decrementing them?

I'm trying to store a few std::string:iterators in a vector, and iterate over them like so:

while (something) {
    for (auto& it : iterators) {
        do_things(*it++);
    }
}

This seems to work - the iterators in the iterators vector mutate their position when incremented. I do not reassign them in the vector, they're the same iterator objects throughout the program.

Is being mutable by incrementing and decrementing guaranteed about any iterator? Or is it safer to treat them as immutable objects and reassign them after changing them? E.g. it = it++;

Upvotes: 0

Views: 179

Answers (1)

eerorika
eerorika

Reputation: 238421

Are iterators specified to be stateful?

They are not "specified" as such, at least not explicitly. Iterators are specified in terms of what operations they support, and what behaviour those operations have.

Containing state is implicit in the abstract concept of what an iterator does, and it is very typical for iterators to conform to that abstract concept. Iterators are an abstraction of pointers. Pointers are stateful.

But it is also possible to define an iterator type that doesn't contain state. Such iterator will necessarily be quite simple. An example would be output iterator that always returns 42 when you indirect through it.

is it safer to treat them as immutable objects and reassign them after changing them? E.g. it = it++;

No. Also if you change them, then you aren't treating them as immutable objects.

Upvotes: 2

Related Questions