从零开始手写STL库:multimap

从零开始手写STL库--multimap的实现

Gihub链接:miniSTL


文章目录


一、multimap是什么?

如图multiset之于set,multimap相当于允许map重复储存键值

所以这里也是增加一个count来计数吗?这里是不可以的

multiset用count是因为key和value相同,而map的key和value是不同的

如果也用count来计数,那么考虑<1,2>和<1,5>的插入,由于key相同,所以后插入的会丢失,这显然不对

所以这里的想法是把红黑树的节点做成list,把所有key相同的值放在一个list中

二、multimap要包含什么函数

明确了设计思路,实际上就是红黑树的一层封装了

如下:

cpp 复制代码
template <typename Key, typename Value> class MultiMap
{
public:
    using ValueType = std::list<Value>; 

    MultiMap() : rbTree(), size(0) {}

    void insert(const Key &key, const Value &value) 
    {
        ValueType *existingValues = rbTree.at(key);
        if (existingValues) existingValues->push_back(value);
        else 
        {
            ValueType values;
            values.push_back(value);
            rbTree.insert(key, values);
        }
        size++;
    }

    void remove(const Key &key) 
    {
        ValueType *existingValues = rbTree.at(key);
        if (existingValues) 
        {
            size -= existingValues->size();
            rbTree.remove(key);
        }
    }

    void remove(const Key &key, const Value &value) 
    {
        ValueType *existingValues = rbTree.at(key);
        if (existingValues) 
        {
            existingValues->remove(value);
            size--;
            if (existingValues->empty()) rbTree.remove(key);
        }
    }

    ValueType *at(const Key &key) { return rbTree.at(key); }

    int getSize() { return size; }

    bool empty() { return size == 0; }

private:
    myRedBlackTree<Key, ValueType> rbTree; 
    size_t size;
};

总结

了解list作为节点代替红黑树常用节点即可,这是multimap实现的基本原理,其他考察点与map相同

相关推荐
lclin_20205 小时前
VS2010兼容|C++系统全能监控工具(彩色界面+日志带单位+完整版)
c++·windows·系统监控·vs2010·编程实战
csdn_aspnet5 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
以神为界6 小时前
Python入门实操:基础语法+爬虫入门+模块使用全指南
开发语言·网络·爬虫·python·安全·web
逻辑驱动的ken6 小时前
Java高频面试题:03
java·开发语言·面试·求职招聘·春招
噜噜大王_7 小时前
深入理解 C 语言内存操作函数:memcpy、memmove、memset、memcmp
c语言·开发语言
广师大-Wzx7 小时前
一篇文章看懂MySQL数据库(下)
java·开发语言·数据结构·数据库·windows·python·mysql
野生技术架构师7 小时前
Java NIO到底是个什么东西?
java·开发语言·nio
lolo大魔王7 小时前
Go语言的异常处理
开发语言·后端·golang
paeamecium7 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
UrSpecial8 小时前
从零实现C++轻量线程池
c++·线程池