三元运算符的意外行为
Unexpected behavior from ternary operator
当我运行这段代码时:
#include <iostream>
#include <map>
using namespace std;
void f1() {
map<int, int> m;
m[5] = m.find(5) == m.end() ? 1 : 2;
cout << m[5] << endl;
}
void f2() {
map<int, int> m;
if (m.find(5) == m.end())
m[5] = 1;
else
m[5] = 2;
cout << m[5] << endl;
}
int main() {
f1();
f2();
return 0;
}
得到以下输出:
2
1
为什么我得到错误的输出,当我使用三元操作符?
函数调用的顺序是不确定的,会影响您的结果。考虑:
void f1()
{
map<int, int> m;
int& result = m[5]; // creates m[5]
auto it = m.find(5); // finds the empty m[5] created above
int value = (it == m.end())? 1: 2;
result = value;
std::cout << m[5] << std::endl;
}
这是你写的代码的一个完全合法的实现。
三元操作符没有问题。这样就可以了:
bool notfound = (m.find(5) == m.end());
m[5] = notfound? 1: 2;
重要的是m[5]
能否先于m.find(5)
求值
在此语句中
m[5] = m.find(5) == m.end() ? 1 : 2;
通过将对象m[5]放在赋值的左侧来创建对象m[5]。因此m.find(5) != m.end(),因为m[5]已经存在。
实际上存在未定义的行为,因为赋值的左操作数和右操作数的求值顺序没有指定。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 使用++运算符会导致意外的结果
- 三元运算符在返回语句中给出意外的结果
- istringstream >>运算符产生意外行为
- 三元运算符在C++中的意外行为
- C++:比较运算符>和字符串文本的意外结果
- C++中三元运算符的意外行为
- 为什么在std :: string上尺寸运算符会产生意外结果
- 位NOT运算符返回意外的负值
- VS2012 std::函数运算符 bool 意外返回 true
- C++ 子类和运算符=:无限循环和意外调用
- boost::运算符的意外行为
- C++新运算符返回新的意外-Dev cpp
- 如果您意外地使用布尔运算符 (||, &&) 比较常量,则发出警告
- C++运算符意外错误
- 三元运算符的意外行为
- 为什么在 std::cout 上显式调用运算符<<会导致意外输出?