Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding const_iterator with pointers?

I'm trying to understand what const_iterator means. I have the following example code:

void CustomerService::RefreshCustomers()
{
    for(std::vector<Customer*>::const_iterator it = customers_.begin();
        it != customers_.end() ; it ++)
    {
        (*it)->Refresh();
    }
}

Refresh() is a method in the Customer class and it is not defined as const. At first thought I thought const_iterator was supposed to disallow modification to the elements of the container. However, this code compiles without complaint. Is this because there's an extra level of indirection going on? What exactly does const_iterator do/mean?

UPDATE

And in a situation like this, is it best practice to use const_iterator?

like image 351
User Avatar asked Nov 04 '11 23:11

User


3 Answers

A const_iterator over a vector<Customer*> will give you a Customer * const not a Customer const*. So you cannot actually change the value being iterated (a pointer), but you sure can change the object pointed to by it. Basically all it says in your case is that you can't do this:

*it = ..something..;
like image 114
K-ballo Avatar answered Sep 28 '22 05:09

K-ballo


You're not modifying the contents of the container. The contents of the container are just pointers. However, you can freely modify whatever the pointers point to.

If you didn't want to be able to modify what the pointers point to, you'd need a vector<const Customer*>.

like image 32
Seth Carnegie Avatar answered Sep 28 '22 05:09

Seth Carnegie


const_iterator is not about whether you can modify the container or not, but about whether you can modify the objects in the container or not. In your case the container contains pointers, and you cannot modify the pointers themselves (any more than you could modify integers...) You can still make call to non-const Refresh() behind a pointer from the collection, because that call does not change the pointer itself.

Difference between const_iterator and iterator is important [only] when your container contains e.g. class instances, not pointers to them, but the instances themselves, for example in a container

list < pair < int , int > >

If 'it' is a const_iterator into this list, you can't do

it->first = 5

but if it is iterator (not const_iterator), that works.

like image 45
Antti Huima Avatar answered Sep 28 '22 03:09

Antti Huima