问题描述
我正在尝试使用C ++ 17功能 std::optional
I was experimenting with C++17 feature std::optional
可选的返回类型为std::optional<std::pair<int, int>>
.我称print_answer
函数中的sum_pair
函数,需要可选打印.
The optional return type is std::optional<std::pair<int, int>>
. I call thesum_pair
function in print_answer
function and wanted a optional print.
在print_answer
函数中,我想检查所需的一对是否具有要显示的东西.就像在以下示例中给出的示例:可选-返回工厂函数可用作while和if
In print_answer
function I wanted to check whether the required pair holds something to show.like in the example given in: optional-returning factory functions are usable as conditions of while and 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;
}
当我使用以下格式的if-else
语句时
When I use the if-else
statement in the following format
(condion) ? print something: print something else;
我收到以下两个错误. (使用GCC 7.1)
I get the following two errors. (used 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?" 吗?
Can somebody explain, why I need to use if-else, but not with "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";
这是有效的C ++.您可以在if
子句的开头条件中添加声明.
this is valid C++. You are allowed to put a declaration in the opening condition of an if
clause.
(auto Pair = sum_pair(vec, sum) )?
std::cout << "Resulting indexes are: " << Pair->first << " " << Pair->second << std::endl
:
std::cout << "Nothing found!\n";
这不是有效的C ++.声明不是表达式.在某些地方允许使用表达式,但不允许使用声明.三元运算符?
的左侧是其中之一.
this is not valid C++. Declarations are not expressions. There are places where expressions are allowed, but declararions are not. The left hand side of ?
, the trinary operator, is one of them.
这篇关于C ++ 17 std ::可选错误:'auto'之前的预期主表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!