0

in the example at http://www.cplusplus.com/reference/map/map/begin/

// map::begin/end
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;
  std::map<char,int>::iterator it;

  mymap['b'] = 100;
  mymap['a'] = 200;
  mymap['c'] = 300;

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

  return 0;
}

why is the iterator it preincremented in the for loop?

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116

1 Answers1

1

BoBTFish's comment is right: the preincrement is used because you wrote it that way. In the rest of my answer I will explain why this option is preferred, i.e., is the recommended practice.

The value of the iterator before the increment is not being used at the point of the expression. The expression just wants to increment the iterator, without using its previous value.

In this case, the preincrement operator is just right and should be preferred. It saves the requirement of storing the value before the increment which exists always for the postincrement operator.

Community
  • 1
  • 1
Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116