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?
Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent.
Use an iteratorAn iterator can be generated to traverse through a vector. vector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence.
You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively. using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector. push_back("a"); myvector.
we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.
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) // ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With