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

相关推荐
a东方青21 分钟前
蓝桥杯 2024 C++国 B最小字符串
c++·职场和发展·蓝桥杯
XiaoyaoCarter2 小时前
每日一道leetcode
c++·算法·leetcode·职场和发展·二分查找·深度优先·前缀树
Blossom.1182 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
da-peng-song2 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive2 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT2 小时前
Qt功能区:简介与安装
开发语言·qt
Hygge-star2 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
Darkwanderor2 小时前
c++STL-list的模拟实现
c++·list
Humbunklung3 小时前
Visual Studio 2022 中添加“高级保存选项”及解决编码问题
前端·c++·webview·visual studio
等等5433 小时前
Java EE初阶——wait 和 notify
java·开发语言