在 C++17 中,如何使用可选元素声明和初始化成对(或元组)向量?
std::vector<std::pair<int, optional<bool> > > vec1 = { {1, true},
{2, false},
{3, nullptr}};
Run Code Online (Sandbox Code Playgroud)
我有一对,其中第二个元素可能为空/可选。
我经常需要为函数使用可选类型:
std::optional<int32_t> get(const std::string& field)
{
auto it = map.find(field);
if (it != map.end()) return it->second;
return {};
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在一行中返回可选值?例如:
std::optional<int32_t> get(const std::string& field)
{
auto it = map.find(field);
return it != map.end() ? it->second : {};
}
Run Code Online (Sandbox Code Playgroud)
导致错误
error: expected primary-expression before '{' token
return it != map.end() ? it->second : {};
^
Run Code Online (Sandbox Code Playgroud)