++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++?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01