Almost every C++ container, such as std::vector includes a begin and end member function. They both return an object of type C::iterator where C is the instantiated container type.
An iterator is like a pointer to one of the elements in a container. A vector iterator supports all the operations which are similar to the operations supported by a pointer to an array element; this includes adding/subtracting to jump between elements and dereferencing to access the referred to element's value.
Suppose there is a std::vector<int> v, then to iterate through that vector using an iterator would look like:
for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
cout << *it << endl;
}
The begin member function returns an iterator to the first element of the vector and the end member function returns an iterator to the non-existing element right past the last element.
Here is a table showing expressions that use an iterator for a hypothetical std::vector<int> v and their corresponding equivalent expression:
Expression using an iterator | Equivalent expression |
---|---|
*v.begin() = 4 | v[0] = 4 |
*(v.begin() + 2) = 10; | v[2] = 10 |
*(v.end() - 1) = 25; | v[v.size() - 1] = 25; |
*(v.end() - v.size()) | v[0] |
*(v.begin() + v.size() - 1) | v[v.size() - 1] |
Once you know how to use iterators, inserting and erasing elements from any standard container should be easy.
Expression | Meaning |
---|---|
v.insert(v.begin() + 4, 24) | Inserts a new element, containing the value 24, into v at index 4. |
v.erase(v.end() - 1) | Erases the last element of v |
Two iterators that are associated with the same container or array represents a range of elements. Many functions in the C++ standard template library require two iterators, first and last, which indicate a range, [first, last), of elements to manipulate or process.
Expression | Meaning |
---|---|
v.insert(v.begin() + 10, u.begin(), u.end()) | Copies the elements from u and inserts them into v at index 10 |
v.insert(v.end(), u.begin() + u.size() / 2) | Copies the first half of elements from u and appends them to v |
v.erase(v.begin(), v.end()) | Erases all elements from v, equivalent to v.clear() |
v.erase(v.begin() + 2, v.begin() + 5) | Erases 2 elements from v starting at index 2. |