map::find和iterator::second可以在一个条件下使用吗
Can map::find and iterator::second be used in one condition
我有这么一段代码:
std::map<int, int> mp;
// do something
auto itor = mp.find(some_value);
if (itor != mp.end() && itor->second == some_other_value) {
// do something
}
我担心首先计算哪个表达式,itor != mp.end()
或 itor->second == some_other_value
?
如果首先评估第二个(可能是因为某些编译器优化?),它可能会出现未定义的行为,因为 itor == mp.end()
可能为真。
我是否应该担心这个问题,所以我必须这样编码:
if (itor != mp.end) {
if (itor->second == some_other_value) {
// do something
}
}
不用担心;你的代码没问题。
如果if (a && b)
的第一个条件为假,则不评估第二个条件。
查找“短路评估”
Wikipedia 有一些信息。
逻辑与 - && - 表达式被计算从左到右 所以 itor != mp.end()
将首先被计算。此外,只有当两个表达式 return 都为真时,它 return 才为真,因此如果第一个为假,则不检查第二个。
所以第一种情况应该可行。
我有这么一段代码:
std::map<int, int> mp;
// do something
auto itor = mp.find(some_value);
if (itor != mp.end() && itor->second == some_other_value) {
// do something
}
我担心首先计算哪个表达式,itor != mp.end()
或 itor->second == some_other_value
?
如果首先评估第二个(可能是因为某些编译器优化?),它可能会出现未定义的行为,因为 itor == mp.end()
可能为真。
我是否应该担心这个问题,所以我必须这样编码:
if (itor != mp.end) {
if (itor->second == some_other_value) {
// do something
}
}
不用担心;你的代码没问题。
如果if (a && b)
的第一个条件为假,则不评估第二个条件。
查找“短路评估”
Wikipedia 有一些信息。
逻辑与 - && - 表达式被计算从左到右 所以 itor != mp.end()
将首先被计算。此外,只有当两个表达式 return 都为真时,它 return 才为真,因此如果第一个为假,则不检查第二个。
所以第一种情况应该可行。