首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::hash <std::optional>

Defined in header <optional>

template<class T> struct hash<std::optional<T>>;

(since C++17)

模板的专门化std::hashstd::optional类允许用户获取包含在optional物品。

专业化std::hash<optional<T>>已启用%28(参见std::hash%29std::hash<std::remove_const_t<T>>已启用,否则将禁用。

当启用时,对象o类型std::optional<T>包含一个值,std::hash<std::optional<T>>()(o)计算值与std::hash<std::remove_const_t<T>>()(*o)对于不包含值的可选选项,未指定散列。

此专门化的成员函数不一定为no,除非基础类型的散列可能抛出。

模板参数

T

-

the type of the value contained in optional object

二次

代码语言:javascript
复制
#include <optional>
#include <unordered_set>
#include <string>
#include <iostream>
using namespace std::literals;
int main()
{
    // hash<optional> makes it possible to use unordered_set
    std::unordered_set<std::optional<std::string>> s = {
            "abc"s, std::nullopt, "def"s
    };
 
    for(const auto& o : s)
        std::cout << o.value_or("(null)") << ' ';
}

二次

可能的产出:

二次

代码语言:javascript
复制
def abc (null)

二次

另见

hash (C++11)

hash function object (class template)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券