【问题标题】:Ternary operator is not working, whereas the same code written using if/else works properly. What am I missing? [closed]三元运算符不起作用,而使用 if/else 编写的相同代码可以正常工作。我错过了什么? [关闭]
【发布时间】:2021-08-07 14:29:37
【问题描述】:

我正在尝试使用哈希图解决 2 sum 问题,我想出了以下代码:

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int,int> comp;
    vector<int> res;
    for (int i = 0; i<nums.size(); i++)
    {   
        (comp.count(target - nums[i])) ? return({comp[target - nums[i]], i}) : comp[nums[i]] = i;
    }

    return res;
}

但它给了我这个错误:

Line 6: Char 46: error: expected expression
        (comp.count(target - nums[i])) ? return({comp[target - nums[i]], i}) : comp[nums[i]] = i;

如果我使用此代码,它可以工作:

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int,int> comp;
    vector<int> res;
    for (int i = 0; i<nums.size(); i++)
    {   
        if(comp.count(target - nums[i]))
            return{comp[target - nums[i]], i};
        else
            comp[nums[i]] = i;                
    }

    return res;
}

三元运算符有什么我不知道的地方,还是语法错误?

【问题讨论】:

标签: c++ vector hashmap


【解决方案1】:

or is 是一个语法错误。

是的,这是语法错误。三元条件运算符的操作数 - 几乎所有其他运算符的操作数 - 必须是表达式。 return 是语句,而不是表达式。

【讨论】:

  • 感谢您的回复。我根据您的建议进行了尝试,并对代码进行了必要的更改。
猜你喜欢
  • 2017-03-25
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 2015-10-07
相关资源
最近更新 更多