可以给 map.end() 赋值吗?
Is it okay to assign values to map.end()?
我想知道像下面的示例那样在地图中的最后一个元素之后分配值 1 是否是一种不好的做法。
using namespace std;
auto chances = map<int, int>{};
chances[0] = 20;
chances[1] = 10;
chances[2] = 30;
int last = 0;
for (auto it = chances.begin(); it != chances.end();) {
last = it->second;
(++it)->second += last;
}
此外,在 for 循环中检查变量是否比检查终止函数更快(循环的这一部分叫什么?)
是的,分配给任何容器(不仅仅是 map
)的 end()
迭代器是不好的做法
在所有标准 C++ 容器中,end()
迭代器不可取消引用。任何对 end()
迭代器取消引用(在本例中为分配)的尝试都是 未定义的行为。
在您的示例代码中,由于使用了预递增运算符,因此取消引用了此 end()
迭代器:
(++it)->second += last
在迭代过程中,当 it
在 end()
之前为 1 时,这将递增 it
并取消引用赋值的结果(结束)。
Also, in a for loop is it faster to check against a variable than a function for termination
通常最好先将终止条件分配给一个常量并与之进行比较。尽管编译器 可以 执行此转换,
有许多因素可能导致函数调用在每次迭代中被重复评估。
说的就是,自己做benchmark,不要过早优化。像这样的小事情很少会产生很大的不同,除非它们处于紧密的循环中。
注意:请尝试每个 SO post 只问 1 个问题,以帮助提高可搜索性并防止它因过于宽泛而被关闭.
Oh and yes, I'm using namespace std;
;)
你应该训练自己不要这样做,因为它是 bad practice that only exists due to legacy。另外,您未来的同事会感谢您。
我想知道像下面的示例那样在地图中的最后一个元素之后分配值 1 是否是一种不好的做法。
using namespace std;
auto chances = map<int, int>{};
chances[0] = 20;
chances[1] = 10;
chances[2] = 30;
int last = 0;
for (auto it = chances.begin(); it != chances.end();) {
last = it->second;
(++it)->second += last;
}
此外,在 for 循环中检查变量是否比检查终止函数更快(循环的这一部分叫什么?)
是的,分配给任何容器(不仅仅是 map
)的 end()
迭代器是不好的做法
在所有标准 C++ 容器中,end()
迭代器不可取消引用。任何对 end()
迭代器取消引用(在本例中为分配)的尝试都是 未定义的行为。
在您的示例代码中,由于使用了预递增运算符,因此取消引用了此 end()
迭代器:
(++it)->second += last
在迭代过程中,当 it
在 end()
之前为 1 时,这将递增 it
并取消引用赋值的结果(结束)。
Also, in a for loop is it faster to check against a variable than a function for termination
通常最好先将终止条件分配给一个常量并与之进行比较。尽管编译器 可以 执行此转换, 有许多因素可能导致函数调用在每次迭代中被重复评估。
说的就是,自己做benchmark,不要过早优化。像这样的小事情很少会产生很大的不同,除非它们处于紧密的循环中。
注意:请尝试每个 SO post 只问 1 个问题,以帮助提高可搜索性并防止它因过于宽泛而被关闭.
Oh and yes, I'm
using namespace std;
;)
你应该训练自己不要这样做,因为它是 bad practice that only exists due to legacy。另外,您未来的同事会感谢您。