为什么迭代器在与map.begin()一起使用时预先增加了

Why is the iterator preincremented when using with map.begin()?

本文关键字:增加 一起 迭代器 map begin 为什么      更新时间:2023-10-16

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;
}

为什么迭代器是在for循环中预先增加的?

BoBTFish的评论是正确的:使用预加密是因为您是这样写的。在我的其余回答中,我将解释为什么此选项是首选,即,这是推荐的做法。

在表达式的点上没有使用增量之前的迭代器的值。表达式只想增加迭代器,而不使用它以前的值。

在这种情况下,预注册操作员是正确的,应该是首选。它保存了在增量之前存储值的要求,这对于后增量运算符来说总是存在的。