迭代地图时++it或it++?

2022-01-10 00:00:00 iteration iterator c++ stdmap

显示如何迭代 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)

即它使用 ++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.

相关文章