Understanding iterator's behavior for std::vector

742 Views Asked by At

I wrote the following simple example:

#include<iostream>
#include<vector>

int main()
{ 
    int arr[] = {1, 2, 4, 7, 10};
    std::vector<int> vect;
    vect.assign(arr, arr + 5);
    for(std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it)
    {
        std::cout << *it << std::endl;
    }

    std::cout << "-------------------------------------" << std::endl;

    for(std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it)
    {
        std::cout << *it << std::endl;
    }
}

DEMO

And both two loops prints the same. My question is is it reliable? Does iterating over the vector return elemtns in the same order every time? I mean, is it standartized or some implementations are allowed to iterating over a vector in the different order. For instance, we iterate over the vector for the firt time as follows:

for(std::vector<int>::iterator it = vect.begin(); it != vect.end(); ++it)
{
    std::cout << *it << std::endl;
}

and get the output

1
2
4
7
10

Whilst, iterating for the second time produce the output:

2
10
1
4
7

Is that possible for some implementation?

2

There are 2 best solutions below

15
On

Yes, it's reliable.

A vector is a "sequence container", which means its ordering is deterministic. You choose the order of the elements in the container, and that's the order you get out of it when you iterate. Always.

  • You populate the vector with elements that live at index 0 to index N-1;
  • A vector's iterator iterates from index 0 to index N-1.

It's completely analogous to walking forwards through an array, in that sense.

Funnily enough, even the associative containers have a reliable iteration order; even though the element ordering is performed by an algorithm using a comparator (which you may specify and, if you don't, it's std::less) rather than simply by virtue of the order in which you appended elements.

You can always rationalise about the iteration order of a standard container.

0
On

std::vector guaranteed continuous memory allocation like an array. So accessing the vector using iterator always guaranteed in same order of elements of a std::vector