Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector, iterators and const_iterator

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;
    }
like image 561
gprex Avatar asked Sep 21 '15 13:09

gprex


People also ask

What is the difference between iterator and const_iterator?

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).

What are vector iterators?

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.

What is the difference between Cbegin and begin?

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.

Can we use iterator in vector?

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.


1 Answers

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.

like image 155
Bo Persson Avatar answered Sep 27 '22 17:09

Bo Persson