Con*_*nst 0 c++ if-statement c++17 stdoptional
我正在尝试 C++17 功能std::optional
可选的返回类型是std::optional<std::pair<int, int>>. 我在函数中调用该
sum_pair函数print_answer并想要一个可选的打印。
在print_answer函数中,我想检查所需的对是否包含要显示的内容。就像下面给出的示例一样:可选返回工厂函数可用作 while 和 if 的条件
以下是代码:这里有错误
#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;
}
Run Code Online (Sandbox Code Playgroud)
当我使用if-else以下格式的语句时
(condion) ? print something: print something else;
Run Code Online (Sandbox Code Playgroud)
我收到以下两个错误。(使用 GCC 7.1)
||=== Build: Debug in MyTestProgram (compiler: GNU GCC Compiler) ===|
|25|error: expected primary-expression before 'auto'|
|25|error: expected ')' before 'auto'|
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下,为什么我需要使用 if-else,而不是“operator”??
if(auto Pair = sum_pair(vec, sum) )
std::cout << "Resulting indexes are: " << Pair->first << " " << Pair->second << std::endl;
else
std::cout << "Nothing found!\n";
Run Code Online (Sandbox Code Playgroud)
这是有效的 C++。您可以将声明放在子句的开头条件中 if。
(auto Pair = sum_pair(vec, sum) )?
std::cout << "Resulting indexes are: " << Pair->first << " " << Pair->second << std::endl
:
std::cout << "Nothing found!\n";
Run Code Online (Sandbox Code Playgroud)
这不是有效的 C++。声明不是表达式。有些地方允许使用表达式,但不允许使用声明。三元运算符的左侧?就是其中之一。