C++ 中三元运算符的意外行为

Unexpected behaviour of ternary operator in C++

以下是我编写的代码片段:

int n,i,j;
map<int,int>mp;
vector<int>vec;
cin>>n;
for(i=0; i<n; i++)
{
    cin>>j;
    mp[j]==0? mp[j]=1,vec.push_back(j): mp[j]=1;
}

对于for循环中的第二行,CodeBlocks-16.01版本显示如下错误:

second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'

但是当我将行更改为:

mp[j]==0? vec.push_back(j), mp[j]=1: mp[j]=1;

没有错误。以下行有什么问题?

mp[j]==0? mp[j]=1,vec.push_back(j): mp[j]=1;

要了解错误,让我们看一下条件运算符的操作数。

第二个操作数:

mp[j]=1, vec.push_back(j)

操作数是由comma operator.
分隔的两个表达式 逗号运算符在这里的工作方式是计算 mp[j]=1 结果值 1,它丢弃该值并计算下一个表达式 vec.push_back(j) 其中 returns void.

因此整个 第二个操作数 最终值 void 类型(这就是错误所说的)。

第三个操作数:

mp[j]=1

此表达式的计算结果为 1,类型为 int。 (因此它不是 voidthrown-exception,这就是错误所说的)。

当你改变第二个操作数时:
在表达式

vec.push_back(j), mp[j]=1

vec.push_back(j) 的计算结果为 void,该值被丢弃,然后 mp[j]=1 的计算结果为 1,类型为 int。现在两个操作数都是 int,因此没有错误。