++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++?
基础教程推荐
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
