pkthapa
pkthapa

Reputation: 1071

Change/update value using std::map const_iterator

I am just curious to know if I can change/update the map's value using const_iterator.

Below is the code snippet:

int main()
{
    map <int, int> m;
    m.insert(make_pair(1, 10));

    map <int, int>::const_iterator itr = m.begin(); //The iterator is const_iterator
    itr->second = 30;

    cout << itr->second; //The value to be printed is 30, and not 10.
    return 0;
}

Thank you in advance for sharing your ideas.

Upvotes: 1

Views: 4218

Answers (5)

eerorika
eerorika

Reputation: 238461

It is not possible to change an element through a const iterator. That's the most important distinction between a const iterator and non-const iterator.

std::map::begin returns a non-const iterator (assuming the object operand is non-const), so there is no need to use a const iterator in the first place.

However, if for some reason (not demonstrated in the example) you can only have a const iterator, but have non-const access to the container, then you can get a non-const iterator to the element pointed by the const iterator. This can be achieved by using following, which looks like a trick:

map <int, int>::iterator mutable_itr = m.erase(itr, itr);

It doesn't erase anything, because [itr, itr) is an empty range.

Upvotes: 3

Oblivion
Oblivion

Reputation: 7374

const iterator is supposed to prevent the user from changing/modiyfing the value by any means.

Upvotes: 1

gsamaras
gsamaras

Reputation: 73444

Can I change/update the map's value using const_iterator?

No!

It's called const iterator for a reason. As mentioned here, A const_iterator is an iterator that points to const value (like a const T* pointer); dereferencing it returns a reference to a constant value (const T&) and prevents modification of the referenced value: it enforces const-correctness.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206737

The compiler should not allow modifying the contents of a map through a const_iterator. The line

itr->second = 30;

should be reported as an error. If your compiler allows that line, then it is not standards compliant. Perhaphs it allows that line to be compiled through flags that allow standards-incompatible behavior.

Using g++, I get the following error.

socc.cc: In function ‘int main()’:
socc.cc:12:19: error: assignment of member ‘std::pair<const int, int>::second’ in read-only object
     itr->second = 30;

Upvotes: 1

Jesper Juhl
Jesper Juhl

Reputation: 31488

The whole point of const_iterator is that it cannot be used to modify the container. So no.

Upvotes: 7

Related Questions