Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding iterator's behavior for std::vector

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?

like image 801
St.Antario Avatar asked Apr 15 '26 22:04

St.Antario


1 Answers

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.

like image 90
Lightness Races in Orbit Avatar answered Apr 18 '26 10:04

Lightness Races in Orbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!