相关疑难解决方法(0)

如何使用可选元素初始化 C++17 对向量

在 C++17 中,如何使用可选元素声明和初始化成对(或元组)向量?

    std::vector<std::pair<int, optional<bool> > > vec1 = { {1, true},
                                                           {2, false}, 
                                                           {3, nullptr}};
Run Code Online (Sandbox Code Playgroud)

我有一对,其中第二个元素可能为空/可选。

c++ vector optional std-pair c++17

36
推荐指数
2
解决办法
2569
查看次数

使用?:运算符返回可选值

我经常需要为函数使用可选类型:

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)

c++ optional c++17

17
推荐指数
2
解决办法
3047
查看次数

标签 统计

c++ ×2

c++17 ×2

optional ×2

std-pair ×1

vector ×1