I have just started learning vectors and iterators. I can't understand 2 things. Why can I change the constant iterator and what is the role of the "*"?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> inventory;
inventory.push_back("inventory1");
inventory.push_back("inventory2");
inventory.push_back("inventory3");
vector<string>::iterator myIterator;
vector<string>::const_iterator iter;
cout << "Your items:\n";
for (iter = inventory.begin(); iter != inventory.end(); iter++)
{
cout << *iter << endl;
}
A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can't be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed).
An iterator is used to move thru the elements an STL container (vector, list, set, map, ...) in a similar way to array indexes or pointers. The * operator dereferences an iterator (ie, is used to access the element an iterator points to) , and ++ (and -- for most iterators) increments to the next element.
begin() returns an iterator to beginning while cbegin() returns a const_iterator to beginning. The basic difference between these two is iterator (i.e begin() ) lets you change the value of the object it is pointing to and const_iterator will not let you change the value of the object.
Use an iterator vector<int>::iterator iter; An iterator is used as a pointer to iterate through a sequence such as a string or vector . The pointer can then be incremented to access the next element in the sequence.
When you do iter = inventory.begin()
it makes iter
refer to the first string in your vector. iter++
moves it to refer to the next string.
In the output you use *iter
as way to access the string that iter
refers to. In the first output that will be inventory1
.
The slight confusion about the constness is that
vector<string>::const_iterator iter;
is an iterator that refers to things that are constant, while
const vector<string>::iterator iter;
would make the iterator itself constant, but allow you to modify the object it refers to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With