Passing over all the elements of a vector is simple, and is usually done using subscripts instead of an iterator. The main advantage of an iterator is that it can be used by many of the functions in <algorithms>. Subscripts provide an easy, familiar way to access vector elements in much the way that array elements would be accessed.
//--- Iterating over vector with subscript. vector<int> v; . . . for (int i=0; i<v.size(); i++) { cout << v[i] << endl; }
&a[n]
is the address of the element after
the last value currently in the array.
//--- Iterating over array with pointer. int a[100]; int n = ...; // current number of elementsWe could loop over this array like this.
for (int* p = &a[0]; p != &a[n]; p++) { cout << *p << endl; }or
for (int* p = a; p != a+n; p++) { cout << *p << endl; }
//--- Iterating over vector with iterator. vector<int> v; . . . for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) { cout << *it << endl; }
list
and map
),
so you must use iterators in many cases.
list
would be more efficient
than a vector
.
vector
use iterators, for example,
assign
, insert
, or erase
.
<algorithm>
functions use iterators.