c++ - Understanding iterator's behavior for std::vector -
i wrote 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 = vect.begin(); != vect.end(); ++it) { std::cout << *it << std::endl; } std::cout << "-------------------------------------" << std::endl; for(std::vector<int>::iterator = vect.begin(); != vect.end(); ++it) { std::cout << *it << std::endl; } }
and both 2 loops prints same. question is reliable? iterating on vector return elemtns in same order every time? mean, standartized or implementations allowed iterating on vector in different order. instance, iterate on vector firt time follows:
for(std::vector<int>::iterator = vect.begin(); != vect.end(); ++it) { std::cout << *it << std::endl; }
and output
1 2 4 7 10
whilst, iterating second time produce output:
2 10 1 4 7
is possible implementation?
yes, it's reliable.
a vector "sequence container", means ordering deterministic. choose order of elements in container, , that's order out of when iterate. always.
- you populate vector elements live @ index 0 index n-1;
- a vector's iterator iterates index 0 index n-1.
it's analogous walking forwards through array, in sense.
funnily enough, associative containers have reliable iteration order; though element ordering performed algorithm using comparator (which may specify and, if don't, it's std::less
) rather virtue of order in appended elements.
you can rationalise iteration order of standard container.
Comments
Post a Comment