Home > Software engineering >  How to understand the first type of pair?
How to understand the first type of pair?

Time:10-21

I am learning C recently and am confused by this data type:

pair<map<string, size_t>::iterator, bool> ret =
            word_count.insert(make_pair(word, 1));

It should be easy to see that we’re defining a pair and that the second type of the pair is bool. The first type of that pair is a bit harder for me to understand. If there were no scope operator or iterator, it would be easy. But after adding :: iterator is it iterator type or the map<string, size_t> type?

CodePudding user response:

iterator is a nested type inside of the std::map class.

The first member of the pair is an iterator to an element in the map. The insert() method returns an iterator to the element that was inserted, or to the element that prevented the insertion.

The bool in the pair indicates whether the insertion was successful or not, ie whether the returned iterator is to a new element or an existing element, respectively.

CodePudding user response:

As you write yourself, the first type is map<string, size_t>::iterator

So what you have is a pair of <iterator, bool>, where the iterator is a map<string, size_t> iterator.

CodePudding user response:

Somewhere in the definition of map<string, size_t> is a statement like typedef [something] iterator; or using iterator = [something];. It introduces map<string, size_t>::iterator as the name for the iterator type associated with map<string, size_t>. So it's an iterator type, but it's specifically the iterator for the map<string, size_t> container.

  •  Tags:  
  • c
  • Related