I need to iterate over a vector strictly in the order the elements were pushed back into it. For my particular case it's better use iterators than iterating though the for-each loop as follows:
std::vector<int> vector;
for(int i = 0; i < vector.size(); i++)
//not good, but works
My question is if it's realiably to iterate over the vector through iterator like that:
std::vector<int> v;
for(typename std::vector<int>::iterator i = v.iterator(); i != v.end(); i++)
//good, but I'm not strictly sure about the iterating order.
So, can I use iterators safely with my requirements? Is it standartized?
Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec.
So, to iterate over a vector in reverse direction, we can use the reverse_iterator to iterate from end to start. vector provides two functions which returns a reverse_iterator i.e. vector::rend() –> Returns a reverse iterator that points to the virtual element before the start of vector.
The [] operator gives you read/write access to an individual element of the vector, such that you can do v[5] = 10 . Put this in a for loop, access the elements based on the index of the loop. The = operator copies all the elements from one vector to another. std::copy copies a range of elements.
C++ Vector Library - rbegin() Function The C++ function std::vector::rbegin() returns a reverse iterator which points to the last element of the vector. Reverse iterator iterates reverse order that is why incrementing them moves towards beginning of vector.
If you have access to C++11 you can use range-based for loops
for (auto i : v)
Otherwise you should use begin()
and end()
for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i)
You can also use std::begin
and std::end
(these require C++11 as well)
for (std::vector<int>::iterator i = std::begin(v); i != std::end(v); ++i)
begin
will return an iterator to the first element in your vector. end
will return an iterator to one element past the end of your vector. So the order in which you get the elements iterating this way is both safe and defined.
if you want to use iterators, your approach is fine
for(auto it = v.begin(); it != v.end(); ++it)
the iteration order depends in fact on the container and the actual used iterator. for a std::vector this code iterates always over the elements in their order in the vector. if you'd use v.rbegin() or v.rend() instead, the order would be reversed. for another container the order is different, for a std::set the very same code would iterate the elements in ascending order of their sorting criterion.
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