Im actually having a hard time understanding what is the function of "const_iterator" Can someone help me or explain it to me? Here the code by the way.
A second characteristic of iterators is whether or not they can be used to modify the values held by their associated container. A constant iterator is one that can be used for access only, and cannot be used for modification. https://stdcxx.apache.org/doc/stdlibug/2-2.html
In C++11 there is cbegin()/cend() / crbegin()/crend() member functions which returns const_iterators. Useful with combination with auto for(auto it = vec.cbegin(); it != vec.cend(); ++it)
A constant iterator is one that can be used for access only, and cannot be used for modification.
If you use a non-const iterator, then you can use that iterator to modify the container. Obviously, if your container is const, then this would violate constness. It is therefore illegal to use a non-const operator with a const container.
If you use a const iterator, you cannot use it to modify the container. It is therefore legal to use a const operator with a const container.
Well, that depends... are you doing anything that would require a const iterator? E.g. the circumstances I explained in my earlier post? Or do you want your iterator to be const for another reason?
Constness is a design decision. You, as the developer, need to decide whether you want entities in your code to be const or not. That applies to iterators, just as much as it does for any other entities.
A constant iterator is just like a regular iterator except that you can't use it to change the element to which it refers, you can think of it as providing read-only access however the iterator itself can change, you can move the constant iterator all around the vector as you see fit, for example suppose you have a vector of string objects that represents bunch of items inside a players inventory, if you just want to display the inventory you're best off using a constant iterator to avoid modifying the objects:
1 2 3 4 5
vector<string>::const_iterator iter;
for ( iter = inventory.begin() ; iter != inventory.end() ; ++iter )
{
cout<<*iter<<endl;
} //Items are protected all thanks to const_iterator.
if you want to modify the objects for whatever reason, you should use a regular iterator:
1 2 3 4 5
vector<string>::iterator iter;
for ( iter = inventory.begin() ; iter != inventory.end() ; ++iter )
{
cout<<*iter<<endl;
} //Items are not constant, they can be modified since iter is not a const_iterator.