Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does map::iterator yield lvalues?

In other words, when i is a map<K,V>::iterator, do the following provide the expected semantics (ie. it modifies the map):

*i = make_pair(k, v);
i->first = k;
i->second = v;

?

Update: The first two lines are invalid, since the return value of operator* is (convertible to?) a pair<const K, V>. What about the third line ?

Assuming a yes answer to the three, this would imply that:

  • Either map<K,V> elements are stored as a pair<K,V> somewhere,
  • Or there is some clever proxy class which map<K,V>::iterator::operator* returns. In this case, how is operator-> implemented ?
like image 325
Alexandre C. Avatar asked Jan 22 '23 09:01

Alexandre C.


1 Answers

I tried to track this down through the standard:

  • For a map<Key,T> the value_type is pair<const Key,T> per 23.3.1/2

  • The map class supports bidirectional iterators, per 23.3.1/1

  • bidirectional iterator satisfies the requirements for forward iterators, per 24.1.4/1

  • For a forward iterator a with value_type T, expression *a returns T& (not a type "convertible to T", as some other iterators do) (Table 74 in 24.1.3)

Therefore, the requirement is to return a reference to pair, and not some other proxy type.

like image 52
Cubbi Avatar answered Feb 08 '23 07:02

Cubbi