++ it或it ++在地图上迭代? [英] ++it or it++ when iterating over a map?

查看:153
本文介绍了++ it或it ++在地图上迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显示如何迭代 std :: map 的示例常常如下:

Examples showing how to iterate over a std::map are often like that:

MapType::const_iterator end = data.end(); 
for (MapType::const_iterator it = data.begin(); it != end; ++it)


b $ b

ie它使用 ++ it 而不是 it ++ 。有什么原因吗?如果我使用 it ++ ,会有什么问题吗?

i.e. it uses ++it instead of it++. Is there any reason why? Could there be any problem if I use it++ instead?

推荐答案

它到测试,我做了三个源文件:

Putting it to the test, I made three source files:

#include <map>

struct Foo { int a; double b; char c; };

typedef std::map<int, Foo> FMap;

### File 1 only ###

void Set(FMap & m, const Foo & f)
{
  for (FMap::iterator it = m.begin(), end = m.end(); it != end; ++it)
    it->second = f;
}

### File 2 only ###

void Set(FMap & m, const Foo & f)
{
  for (FMap::iterator it = m.begin(); it != m.end(); ++it)
    it->second = f;
}

### File 3 only ###

void Set(FMap & m, const Foo & f)
{
  for (FMap::iterator it = m.begin(); it != m.end(); it++)
    it->second = f;
}

### end ###

使用 g ++ -S -O3 ,GCC 4.6.1编译,我发现版本2和3产生相同的程序集,版本1仅在一条指令, cmpl%eax,%esi vs cmpl%esi,%eax

After compiling with g++ -S -O3, GCC 4.6.1, I find that version 2 and 3 produce identical assembly, and version 1 differs only in one instruction, cmpl %eax, %esi vs cmpl %esi, %eax.

所以,选择和使用任何适合你的风格。前缀增量 ++ it 可能是最好的,因为它最准确地表达您的要求,但不会挂起。

So, take your pick and use whatever suits your style. Prefix increment ++it is probably best because it expresses your requirements most accurately, but don't get hung up about it.

这篇关于++ it或it ++在地图上迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆