zoukankan      html  css  js  c++  java
  • set, unordered_set模板类

    template<
        class Key,
        class Hash = std::hash<Key>,
        class KeyEqual = std::equal_to<Key>,
        class Allocator = std::allocator<Key>
    > class unordered_set;
    抽时间实现上述哈希表的简易模板。
    =======================================================================================================================

    std::unordered_set<std::pair<int, int>> S;

    以上的声明是无法通过编译的。unordered_set的模板类声明如下。一般情况下,我们只需声明Key即可, Hash, KetEqual等会自动推导出来。

    template<
        class Key,
        class Hash = std::hash<Key>,
        class KeyEqual = std::equal_to<Key>,
        class Allocator = std::allocator<Key>
    > class unordered_set;

    很遗憾的是,标准库中并没有实现std::hash<std::pair<class T1, classT2>>. 可参考网页链接Hash模板

    我们需要手动实现std::hash<std::pair<class T1, classT2>>., 而KeyEqual与Allocator无需手动实现。

    unordered_set/unordered_map会保证容器内任意两元素x, y, equal_to(x, y)为false.

    而set模板类声明如下。

    template<
        class Key,
        class Compare = std::less<Key>,
        class Allocator = std::allocator<Key>
    > class set;

    set/map会保证容器内任意两元素x, y, std::less<Key>(x, y), std::less<Key>(y, x)一个为True,一个为False。

    namespace std {
        template<typename T1, typename T2>
        struct hash<std::pair<T1, T2>> {
            std::size_t operator() (const std::pair<T1, T2> &a) const {
                return 0;
            }
        };
        
        template<typename T1, typename T2>
        struct equal_to<std::pair<T1, T2>> {
            bool operator()( const std::pair<T1, T2>& lhs, const std::pair<T1, T2>& rhs ) const {
                return 0;
            }
        };
        
        template<typename T1, typename T2>
        struct less<std::pair<T1, T2>> {
            bool operator()( const std::pair<T1, T2>& lhs, const std::pair<T1, T2>& rhs ) const {
                return 0;
            }
        };
    };
  • 相关阅读:
    jquery使用
    网站重构?
    WEB应用从服务器主动推送Data到客户端有那些方式?
    异步加载和延迟加载?
    平时如何管理你的项目?
    对前端界面工程师这个职位是怎么样理解的?它的前景会怎么样?
    约定优于配置(convention over configuration)
    JavaEE的13种核心技术
    The Spring Framework ConfigurableListableBeanFactory.java
    mySQL的boolean类型为tinyint(1)
  • 原文地址:https://www.cnblogs.com/dirge/p/9515323.html
Copyright © 2011-2022 走看看