3.4. Introducing IteratorsWhile we can use subscripts to access the elements in a vector, the library also gives us another way to examine elements: We can use an iterator. An iterator is a type that lets us examine the elements in a container and navigate from one element to another. The library defines an iterator type for each of the standard containers, including vector. Iterators are more general than subscripts: All of the library containers define iterator types, but only a few of them support subscripting. Because iterators are common to all containers, modern C++ programs tend to use iterators rather than subscripts to access container elements, even on types such as vector that support subscripting. The details of how iterators work are discussed in Chapter 11, but we can use them without understanding them in their full complexity. Container iterator TypeEach of the container types, such as vector, defines its own iterator type: vector<int>::iterator iter; This statement defines a variable named iter, whose type is the type named iterator defined by vector<int>. Each of the library container types defines a member named iterator that is a synonym for the actual type of its iterator.
The begin and end OperationsEach container defines a pair of functions named begin and end that return iterators. The iterator returned by begin refers to the first element, if any, in the container: vector<int>::iterator iter = ivec.begin(); This statement initializes iter to the value returned by the vector operation named begin. Assuming the vector is not empty, after this initialization, iter refers to the same element as ivec[0]. The iterator returned by the end operation is an iterator positioned "one past the end" of the vector. It is often referred to as the off-the-end iterator indicating that it refers to a nonexistent element "off the end" of the vector. If the vector is empty, the iterator returned by begin is the same as the iterator returned by end.
Dereference and Increment on vector IteratorsThe operations on iterator types let us retrieve the element to which an iterator refers and let us move an iterator from one element to another. Iterator types use the dereference operator (the * operator) to access the element to which the iterator refers: *iter = 0; The dereference operator returns the element that the iterator currently denotes. Assuming iter refers to the first element of the vector, then *iter is the same element as ivec[0]. The effect of this statement is to assign 0 to that element. Iterators use the increment operator (++) (Section 1.4.1, p. 13) to advance an iterator to the next element in the container. Incrementing an iterator is a logically similar operation to the increment operator when applied to int objects. In the case of ints, the effect is to "add one" to the int's value. In the case of iterators, the effect is to "advance the iterator by one position" in the container. So, if iter refers to the first element, then ++iter denotes the second element.
Other Iterator OperationsAnother pair of useful operations that we can perform on iterators is comparison: Two iterators can be compared using either == or !=. Iterators are equal if they refer to the same element; they are unequal otherwise. A Program that Uses IteratorsAssume we had a vector<int> named ivec and we wanted to reset each of its elements to zero. We might do so by using a subscript: // reset all the elements in ivec to 0 for (vector<int>::size_type ix = 0; ix != ivec.size(); ++ix) ivec[ix] = 0; This program uses a for loop to iterate through the elements in ivec. The for defines an index, which it increments on each iteration. The body of the for sets each element in ivec to zero. A more typical way to write this loop would use iterators: // equivalent loop using iterators to reset all the elements in ivec to 0 for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter) *iter = 0; // set element to which iter refers to 0 The for loop starts by defining iter and initializing it to refer to the first element in ivec. The condition in the for tests whether iter is unequal to the iterator returned by the end operation. Each iteration increments iter. The effect of this for is to start with the first element in ivec and process in sequence each element in the vector. Eventually, iter will refer to the last element in ivec. After we process the last element and increment iter, it will become equal to the value returned by end. At that point, the loop stops. The statement in the for body uses the dereference operator to access the value of the current element. As with the subscript operator, the value returned by the dereference operator is an lvalue. We can assign to this element to change its value. The effect of this loop is to assign the value zero to each element in ivec. Having walked through the code in detail, we can see that this program has exactly the same effect as the version that used subscripts: We start at the first element in the vector and set each element in the vector to zero.
const_iteratorThe previous program used a vector::iterator to change the values in the vector. Each container type also defines a type named const_iterator, which should be used when reading, but not writing to, the container elements. When we dereference a plain iterator, we get a nonconst reference (Section 2.5, p. 59) to the element. When we dereference a const_iterator, the value returned is a reference to a const (Section 2.4, p. 56) object. Just as with any const variable, we may not write to the value of this element. For example, if text is a vector<string>, we might want to traverse it, printing each element. We could do so as follows: // use const_iterator because we won't change the elements for (vector<string>::const_iterator iter = text.begin(); iter != text.end(); ++iter) cout << *iter << endl; // print each element in text This loop is similar to the previous one, except that we are reading the value from the iterator, not assigning to it. Because we read, but do not write, through the iterator, we define iter to be a const_iterator. When we dereference a const_iterator, the value returned is const. We may not assign to an element using a const_iterator: for (vector<string>::const_iterator iter = text.begin(); iter != text.end(); ++ iter) *iter = " "; // error: *iter is const When we use the const_iterator type, we get an iterator whose own value can be changed but that cannot be used to change the underlying element value. We can increment the iterator and use the dereference operator to read a value but not to assign to that value. A const_iterator should not be confused with an iterator that is const. When we declare an iterator as const we must initialize the iterator. Once it is initialized, we may not change its value: vector<int> nums(10); // nums is nonconst const vector<int>::iterator cit = nums.begin(); *cit = 1; // ok: cit can change its underlying element ++cit; // error: can't change the value of cit A const_iterator may be used with either a const or nonconst vector, because it cannot write an element. An iterator that is const is largely useless: Once it is initialized, we can use it to write the element it refers to, but cannot make it refer to any other element. const vector<int> nines(10, 9); // cannot change elements in nines // error: cit2 could change the element it refers to and nines is const const vector<int>::iterator cit2 = nines.begin(); // ok: it can't change an element value, so it can be used with a const vector<int> vector<int>::const_iterator it = nines.begin(); *it = 10; // error: *it is const ++it; // ok: it isn't const so we can change its value
// an iterator that cannot write elements vector<int>::const_iterator // an iterator whose value cannot change const vector<int>::iterator
3.4.1. Iterator ArithmeticIn addition to the increment operator, which moves an iterator one element at a time, vector iterators (but few of the other library container iterators) also support other arithmetic operations. These operations are referred to as iterator arithmetic, and include:
We can use iterator arithmetic to move an iterator to an element directly. For example, we could locate the middle of a vector as follows: vector<int>::iterator mid = vi.begin() + vi.size() / 2; This code initializes mid to refer to the element nearest to the middle of ivec. It is more efficient to calculate this iterator directly than to write an equivalent program that increments the iterator one by one until it reaches the middle element.
![]() |