我有一个 char vector arr 和一个 vector arrnode 其元素为 node 。以下是代码:
struct node
{
int min;
int sum;
};
vector<char> arr;
char c;
for(int j = 0; j < n; j++)
{
cin >> c;
arr.push_back(c);
}
vector<node> arrnode;
for(int j = 0; j < n; j++)
{
/* if(arr[j]=='(')
arrnode.push_back({1,1});
else
arrnode.push_back({-1,-1});*/
arrnode.push_back( ( ( arr[j]=='(' ) ? {1,1} : {-1,-1} ) );
}
此代码在使用三元运算符的行中出现以下错误。
prog.cpp:68:49: error: expected ‘:’ before ‘{’ token
prog.cpp:68:49: error: expected primary-expression before ‘{’ token
但是,if-else 部分(已注释)使代码可以正常工作。我错过了什么? 在此先感谢并为问题的破旧标题感到抱歉:)
最佳答案
所以使用 gcc
你看到的错误看起来像这样:
error: expected primary-expression before ‘{’ token
它需要一个表达式,但 {}
不是表达式,它们仅可用于某些地方的列表初始化,如 8.5.4
部分所指定draft standard ,它说:
... List-initialization can be used
— as the initializer in a variable definition (8.5)
— as the initializer in a new expression (5.3.4)
— in a return statement (6.6.3)
....
它没有列出条件运算符
。正如其他人所说,另一种方法是使用 if
语句。尽管正如 James 指出的那样,这可能不是理想的替代方法,所以如果您觉得 conditional operator
在您的上下文中效果更好,那么正如 James 所建议的那样,只需使用以下内容:
arrnode.push_back( arr[j] == '(' ? node( 1, 1 ) : node( -1, -1 ) );
关于c++ - 编译器不接受三元运算符的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17786555/