Declaring const_iterator vs declaring an iterator const
An iterator acts much like a T* pointer.
Declare an iterator const
Declaring an iterator const is nothing but declaring a const pointer which is equivalent to T* const - iterator is not allowed to point to different object, but the data iter points to can be modified.
Lets look at an example below :
std::vector<std::string> vecOfStrings;
// Push some strings to the vector
// Declare an iterator const
const std::vector<string>::iterator iter; // iter acts like T* const , const pointer
iter = vecOfStrings.begin();
*iter = "newValue"; // Ok, changes the value what iter points to.
++iter; // Compilation error , iter is const
Declare an const_iterator
Declaring an const_iterator is nothing but declaring an pointer to const object which is equivalent to const T* - Iterator can point to different object but modifying the data will throw an compilation error.
Let's look at an example below :
std::vector<std::string> vecOfStrings;
// Push some strings to the vector.
std::vector<string>::const_iterator cIter; // iter acts like const T* , pointer to const // object
*cIter= "newValue"; // Compilation error, iter is const
++cIter; //Ok, increments to the next value.
Comments
Post a Comment