Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAP C++ using itr.first->second VS itr->second

Tags:

c++

In http://www.cplusplus.com/reference/map/map/insert/, I am confused with the reasoning of doing ret.first->second or it->second to access the 2nd value. Why was it necessary to do .first->second if you can do it with just ->second?

// map::insert (C++98)
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;
  std::pair<std::map<char,int>::iterator,bool> ret;
  ret = mymap.insert ( std::pair<char,int>('z',500) );
  if (ret.second==false) {
    std::cout << "element 'z' already existed";
    std::cout << " with a value of " << ret.first->second << '\n';
  }

  // showing contents:
  std::cout << "mymap contains:\n";
  for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
    std::cout << it->first << " => " << it->second << '\n';

  return 0;
}
like image 870
leon Avatar asked Mar 20 '26 23:03

leon


1 Answers

Each std::map element is stored as a std::pair containing its key and value (in the pair's first and second fields, respectively).

The std::map::insert() method returns a std::pair containing:

  • a std::map::iterator pointing at the std::map element for the key which is being inserted.

  • a bool indicating whether that element has been newly inserted or it already existed in the std::map.

When the code calls ret = mymap.insert(...);, ret.first is the iterator and ret.second is the bool.

Dereferencing a std::map::iterator accesses the key/value std::pair of the element which the iterator is pointing at.

Thus, since ret.first is a std::map::iterator, then ret.first->first is the element's key and ret.first->second is the element's value.

In the subsequent loop, for (it=mymap.begin(); it!=mymap.end(); ++it), it is also a std::map::iterator, pointing at a different element of the std::map on each loop iteration. Thus, when dereferencing that iterator, it->first is the element's key and it->second is the element's value.

like image 102
Remy Lebeau Avatar answered Mar 22 '26 13:03

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!