TheDoomDestroyer
TheDoomDestroyer

Reputation: 3025

Vector iterators < or !=

Could anyone help me understand whether there's a big difference in != and < when it comes to talk about vector iterators within a for loop?

I mean, no matter whether you use != and <, the result should be the same?

for (vector<int>::iterator i = vec.begin(); i != vec.end(); i++)
    // DO STUFF
for (vector<int>::iterator i = vec.begin(); i < vec.end(); i++)
    // DO STUFF

I am aware that the most common way is to use !=, but would < be a big issue if used?

Upvotes: 30

Views: 3202

Answers (3)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

operator< is only supported for random access iterators. std::vector::iterator is a random access iterator, so both i != vec.end() and i < vec.end() are supported and valid and make no difference in your example.

If you had a container that does not support random access iterators (e.g. std::list), i < list.end() would not compile.

The general recommendation is to use postfix increment only when it is necessary though because it may create an unnecessary copy when the iterator is non-trivial, so ++i is cleaner and may be faster.

Also, if the loop calls a function whose definition is not available in this translation unit vec.end() is going to be reloaded from memory on each loop iteration, which might cause an unnecessary cache miss. You can avoid that reload by saving the value into a local variable, so that the compiler is certain that the local variable is inaccessible to any other function:

for(vector<int>::iterator i = vec.begin(), j = vec.end(); i < j; ++i)
    // ...

Even better, you may like to use range-for loops that avoid these performance pitfalls for you:

for(auto const& elem : vec)
    // ...

Upvotes: 40

Galik
Galik

Reputation: 48635

The entire philosophy behind the STL part of the Standard Library (the containers, iterators and algorithms) is to minimize the programatic distinctions between the containers. They exhibit different properties but how you program them is designed to be as similar as possible.

This makes them easier to learn and easier to use generically. That means you can write one generic function (or algorithm) and have it apply to any other container (or as many as possible).

With that in mind it is beneficial to use syntax that is common to all containers and iterators where possible.

Only some containers' iterators allow < comparisons but all containers' iterators accept !=. For that reason I would recommend always using != as a matter of consistency and to facilitate your code being easily ported to a different container.

Upvotes: 11

Demosthenes
Demosthenes

Reputation: 1535

It does make a difference, although not for std::vector. All iterators are equality comparable, so != will always work. Only random access iterators are less than comparable, as is std::vector, so in your case it wouldn't be a big issue.

Upvotes: 9

Related Questions