++it or it++ when iterating over a map?(迭代地图时++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)
即它使用 ++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或it++?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
