++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++?
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01