【发布时间】: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