从零开始手写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相同

相关推荐
研☆香5 小时前
js中 onload 事件的用法
开发语言·javascript·ecmascript
软行5 小时前
LeetCode 每日一题 3876. 构造奇偶一致的数组 II
c++·算法·leetcode
xiancai_xianyu6 小时前
想把数据模型一次建完美再上AI?会一直卡在建模里
开发语言·人工智能·php·数据模型·语义层·本体建模·企业知识网络
繁星蓝雨6 小时前
C++设计原理———重载(extern “C“的由来、顺序依赖、语义依赖、overload、名称修饰符、对象操作、运算符重载、新增运算符、枚举和布尔类型)
c语言·c++·extern c·overload·重载·语义依赖·顺序依赖
handler016 小时前
【Linux】虚拟地址空间解析
linux·运维·c++·线程·进程·虚拟地址空间·虚拟地址
(Charon)6 小时前
【C++】网络缓冲区设计(二):Ring Buffer环形缓冲区、head/tail与跨界读写
开发语言·c++
码匠许师傅6 小时前
【设计模式精讲】24.观察者模式(Observer)
c++·观察者模式·设计模式·uml
Java后端的Ai之路6 小时前
LangChain Deep Agents 从入门到企业实战
开发语言·人工智能·python·langchain·deepagents
小刘在重生~6 小时前
Java 集合|Collection、List、ArrayList、LinkedList、泛型、Collections 工具类
java·数据结构·list
会飞的拖把6 小时前
Python文件操作详解:从文件读写到os、shutil模块实战
开发语言·python