C++ 自定义STL容器的内存分配器(map、set、vector、string、unordered_map、unordered_set)

159 篇文章 1 订阅
文章介绍了如何在C++代码中根据编译器版本设置标准,如C++11/14/17,并展示了针对不同编译器标准的代码片段,包括`Voidify_iter`模板函数以及`allocator`类的实现,涉及容器类型如`std::list`,`std::vector`,等。
摘要由CSDN通过智能技术生成

注意:

使用 C++ 11/14 标准以上应注释下述代码并恢复上述被注释的代码,即设置编译器选项标准为:-std=cxx1z、-std=cxx2a。

        // C++ 17...cxx1z
        //template <class _Iter>
        //constexpr void* _Voidify_iter(_Iter _It) noexcept {
        //    if constexpr (std::is_pointer<_Iter>::value) {
        //        return const_cast<void*>(static_cast<const volatile void*>(_It));
        //    }
        //    else {
        //        return const_cast<void*>(static_cast<const volatile void*>(std::addressof(*_It)));
        //    }
        //}

        // C++ 11...cxx0x
        // C++ 14...cxx1y
        template <typename _Iter>
        typename std::enable_if<std::is_pointer<_Iter>::value, void*>::type
        constexpr _Voidify_iter(_Iter _It) noexcept {
            return const_cast<void*>(static_cast<const volatile void*>(_It));
        }

        template <typename _Iter>
        typename std::enable_if<!std::is_pointer<_Iter>::value, void*>::type
        constexpr _Voidify_iter(_Iter _It) noexcept {
            return const_cast<void*>(static_cast<const volatile void*>(std::addressof(*_It)));
        }

当然你可以选择判定编译器宏:__cplusplus 

if (__cplusplus == 201703L)
    std::cout << "C++17\n";
else if (__cplusplus == 201402L)
    std::cout << "C++14\n";
else if (__cplusplus == 201103L)
    std::cout << "C++11\n";
else if (__cplusplus == 199711L)
    std::cout << "C++98\n";
else if (__cplusplus == 202002L)
    std::cout << "C++20\n";

else
    std::cout << "pre-standard C++\n";

头文件定义:

    template <class _Ty>
    class allocator {
    public:
        static_assert(!std::is_const<_Ty>::value, "The C++ Standard forbids containers of const elements "
            "because allocator<const T> is ill-formed.");

        using _From_primary = allocator;

        using value_type = _Ty;

        using pointer = _Ty*;
        using const_pointer = const _Ty*;

        using reference = _Ty&;
        using const_reference = const _Ty&;

        using size_type = size_t;
        using difference_type = ptrdiff_t;

        using propagate_on_container_move_assignment = std::true_type;
        using is_always_equal = std::true_type;

        template <class _Other>
        struct rebind {
            using other = allocator<_Other>;
        };

        _Ty* address(_Ty& _Val) const noexcept {
            return std::addressof(_Val);
        }

        const _Ty* address(const _Ty& _Val) const noexcept {
            return std::addressof(_Val);
        }

        constexpr allocator() noexcept {}
        constexpr allocator(const allocator&) noexcept = default;

        template <class _Other>
        constexpr allocator(const allocator<_Other>&) noexcept {}

        ~allocator() = default;
        allocator& operator=(const allocator&) = default;

        void deallocate(_Ty* const _Ptr, const size_t _Count) {
            assert((_Ptr != nullptr || _Count == 0) && "null pointer cannot point to a block of non-zero size");
            // no overflow check on the following multiply; we assume _Allocate did that check
            ppp::Mfree(_Ptr);
        }

        _Ty* allocate(const size_t _Count) {
            static_assert(sizeof(value_type) > 0, "value_type must be complete before calling allocate.");

            void* memory = (void*)ppp::Malloc(sizeof(_Ty) * _Count);
            return static_cast<_Ty*>(memory);
        }

        _Ty* allocate(const size_t _Count, const void*) {
            return allocate(_Count);
        }

        // C++ 17...cxx1z
        //template <class _Iter>
        //constexpr void* _Voidify_iter(_Iter _It) noexcept {
        //    if constexpr (std::is_pointer<_Iter>::value) {
        //        return const_cast<void*>(static_cast<const volatile void*>(_It));
        //    }
        //    else {
        //        return const_cast<void*>(static_cast<const volatile void*>(std::addressof(*_It)));
        //    }
        //}

        // C++ 11...cxx0x
        // C++ 14...cxx1y
        template <typename _Iter>
        typename std::enable_if<std::is_pointer<_Iter>::value, void*>::type
        constexpr _Voidify_iter(_Iter _It) noexcept {
            return const_cast<void*>(static_cast<const volatile void*>(_It));
        }

        template <typename _Iter>
        typename std::enable_if<!std::is_pointer<_Iter>::value, void*>::type
        constexpr _Voidify_iter(_Iter _It) noexcept {
            return const_cast<void*>(static_cast<const volatile void*>(std::addressof(*_It)));
        }

        template <class _Objty, class... _Types>
        void construct(_Objty* const _Ptr, _Types&&... _Args) {
            ::new (_Voidify_iter(_Ptr)) _Objty(std::forward<_Types>(_Args)...);
        }

        template <class _Uty>
        void destroy(_Uty* const _Ptr) {
            _Ptr->~_Uty();
        }

        size_t max_size() const noexcept {
            return static_cast<size_t>(-1) / sizeof(_Ty);
        }

        // The number of user bytes a single byte of ASAN shadow memory can track.
        static constexpr size_t _Asan_granularity = 8;
        static constexpr size_t _Minimum_allocation_alignment = _Asan_granularity;
    };

    using string = std::basic_string<char, std::char_traits<char>, allocator<char>>;

    template <typename TValue>
    using list = std::list<TValue, allocator<TValue>>;

    template <typename TValue>
    using vector = std::vector<TValue, allocator<TValue>>;

    template <typename TValue>
    using set = std::set<TValue, std::less<TValue>, allocator<TValue>>;

    template <typename TKey, typename TValue>
    using map = std::map<TKey, TValue, std::less<TKey>, allocator<std::pair<const TKey, TValue>>>;

    template <typename TValue>
    using unordered_set = std::unordered_set<TValue, std::hash<TValue>, std::equal_to<TValue>, allocator<TValue>>;

    template <typename TKey, typename TValue>
    using unordered_map = std::unordered_map<TKey, TValue, std::hash<TKey>, std::equal_to<TKey>, allocator<std::pair<const TKey, TValue>>>;

回答: 在C++中,map、unordered_mapset和unordered_set都是STL(标准模板库)中的容器。它们都用于存储一组数据,并提供了不同的功能和性能特点。 map是一个有序的关联容器,它使用红黑树实现,可以根据键值进行快速查找。map中的元素按照键值的大小进行排序,并且每个键值只能出现一次。\[1\]unordered_map是一个无序的关联容器,它使用哈希表实现,可以根据键值进行快速查找。unordered_map中的元素没有特定的顺序,并且每个键值只能出现一次。\[2\] set是一个有序的容器,它使用红黑树实现,可以存储不重复的元素。set中的元素按照值的大小进行排序,并且每个值只能出现一次。\[3\]unordered_set是一个无序的容器,它使用哈希表实现,可以存储不重复的元素。unordered_set中的元素没有特定的顺序,并且每个值只能出现一次。 在使用这些容器时,可以使用insert()函数插入元素,使用find()函数查找元素,使用erase()函数删除元素。此外,map和unordered_map还提供了count()函数来计算特定键值的出现次数。 总结来说,map和unordered_map适用于需要根据键值进行快速查找的场景,set和unordered_set适用于需要存储不重复元素的场景。具体选择哪个容器取决于你的需求和性能要求。 #### 引用[.reference_title] - *1* *3* [C++map,unordered_map,set和unordered_set的用法和区别](https://blog.csdn.net/bryant_zhang/article/details/111600209)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [初识C++之unordered_map与unordered_set](https://blog.csdn.net/Masquerena114514/article/details/129938734)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值