【问题标题】:C++17 std::optional error: expected primary-expression before 'auto'C++17 std::optional 错误:“auto”之前的预期主表达式
【发布时间】:2018-07-15 19:49:31
【问题描述】:

我正在试验 C++17 功能 std::optional

可选的返回类型是std::optional<std::pair<int, int>>。我打电话给 sum_pair 函数在 print_answer 函数中,并且想要一个可选的打印。

print_answer 函数中,我想检查所需的对是否包含要显示的内容。 就像下面给出的例子:optional-returning factory functions are usable as conditions of while and if

以下是代码:here is it live with error

#include <iostream>
#include <vector>
#include <unordered_map>
#include <optional>

typedef std::optional<std::pair<int, int>> returnType;

// following algorithum works fine: just to show, 
// how I have used the std::optional
returnType sum_pair(const std::vector<int>& vec, const int sum)
{
    std::unordered_map<int, int> compIndexMap;

    int index = 0;
    for(const int& ele: vec)
    {
        if(auto check = compIndexMap.find(sum - ele); check != compIndexMap.cend())
            return returnType{std::make_pair(check->second, index)};

        compIndexMap.emplace(sum - ele, index);
        ++index;
    }
    return std::nullopt;
}

// problem is here:
void print_answer(const std::vector<int>& vec, const int sum)
{
    // if I uncomment the if-else, everything works
    /*if*/(auto Pair = sum_pair(vec, sum) )?  
        std::cout << "Resulting indexes are: " << Pair->first << " " << Pair->second << std::endl: //;
    //else
        std::cout << "Nothing found!\n";
}
int main()
{
    std::vector<int> vec0{ 1,3,2,8 };
    const int sum = 8;
    print_answer(vec0, sum);
    return 0;
}

当我使用以下格式的if-else 语句时

(condion) ? print something: print something else;

我收到以下两个错误。 (使用 GCC 7.1)

||=== Build: Debug in MyTestProgram (compiler: GNU GCC Compiler) ===|
|25|error: expected primary-expression before 'auto'|
|25|error: expected ')' before 'auto'|

谁能解释一下,为什么我需要使用 if-else,而不是 "operator ?"

【问题讨论】:

  • auto anything = something 不是有效的表达式。这是一个声明,声明不是有效的表达式。而且三元表达式不是 if-else 语句。
  • @n.m.抱歉没有明白你的意思。那么this 怎么会起作用?
  • 让我再试一次。一个? operator 不是 if-else 语句,并不是所有在后者中可以接受的东西都在前者中是可以接受的。
  • @Malayalam 你希望(int x = 17) ? x + 3 : x + 5 编译吗?

标签: c++ if-statement c++17 stdoptional


【解决方案1】:
if(auto Pair = sum_pair(vec, sum) )
    std::cout << "Resulting indexes are: " << Pair->first << " " << Pair->second << std::endl;
else
    std::cout << "Nothing found!\n";

这是有效的 C++。您可以在if 子句的开始条件中声明。

(auto Pair = sum_pair(vec, sum) )?
    std::cout << "Resulting indexes are: " << Pair->first << " " << Pair->second << std::endl
:
    std::cout << "Nothing found!\n";

这不是有效的 C++。声明不是表达式。有些地方允许使用表达式,但不允许使用声明。三元运算符?的左边就是其中之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2015-03-31
    • 2012-07-08
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多