Qt :Ordered Map

在项目中,有时候对数据结构有这样的需求,既需要具备Map的高效读写,又要兼具插入数据成员的有序性,这时候你就需要使用Ordered Map了。
关于Ordered Map,相关资源比较多,实现思路比较简单,基本上都是通过list有序记录插入的数据的key值,重写遍历或者迭代的方法时,限定按照key的插入顺序遍历。
笔者只是在这里推荐一个现成的开源项目:《Qt Ordered Map》

#ifndef ORDEREDMAP_H
#define ORDEREDMAP_H

#include <QtGlobal>
#include <QHash>
#include <QLinkedList>
#include <QList>
#include <QPair>

#ifdef Q_COMPILER_INITIALIZER_LISTS
#include <initializer_list>
#endif

template <typename Key> inline bool oMHashEqualToKey(const Key &key1, const Key &key2)
{
    // Key type must provide '==' operator
    return key1 == key2;
}

template <typename Ptr> inline bool oMHashEqualToKey(Ptr *key1, Ptr *key2)
{
    Q_ASSERT(sizeof(quintptr) == sizeof(Ptr *));
    return quintptr(key1) == quintptr(key2);
}

template <typename Ptr> inline bool oMHashEqualToKey(const Ptr *key1, const Ptr *key2)
{
    Q_ASSERT(sizeof(quintptr) == sizeof(const Ptr *));
    return quintptr(key1) == quintptr(key2);
}

template <typename Key, typename Value>
class OrderedMap
{
    class OMHash;

    typedef typename QLinkedList<Key>::iterator QllIterator;
    typedef typename QLinkedList<Key>::const_iterator QllConstIterator;
    typedef QPair<Value, QllIterator> OMHashValue;

    typedef typename OMHash::iterator OMHashIterator;
    typedef typename OMHash::const_iterator OMHashConstIterator;

public:

    class iterator;
    class const_iterator;

    typedef typename OrderedMap<Key, Value>::iterator Iterator;
    typedef typename OrderedMap<Key, Value>::const_iterator ConstIterator;

    explicit OrderedMap();

#ifdef Q_COMPILER_INITIALIZER_LISTS
    OrderedMap(std::initializer_list<std::pair<Key,Value> > list);
#endif

    OrderedMap(const OrderedMap<Key, Value>& other);

#if (QT_VERSION >= 0x050200)
    OrderedMap(OrderedMap<Key, Value>&& other);
#endif

    void clear();

    bool contains(const Key &key) const;

    int count() const;

    bool empty() const;

    iterator insert(const Key &key, const Value &value);

    bool isEmpty() const;

    QList<Key> keys() const;

    int remove(const Key &key);

    int size() const;

    Value take(const Key &key);

    Value value(const Key &key) const;

    Value value(const Key &key, const Value &defaultValue) const;

    QList<Value> values() const;

    OrderedMap<Key, Value> & operator=(const OrderedMap<Key, Value>& other);

#if (QT_VERSION >= 0x050200)
    OrderedMap<Key, Value> & operator=(OrderedMap<Key, Value>&& other);
#endif

    bool operator==(const OrderedMap<Key, Value> &other) const;

    bool operator!=(const OrderedMap<Key, Value> &other) const;

    Value& operator[](const Key &key);

    const Value operator[](const Key &key) const;

    iterator begin();

    const_iterator begin() const;

    iterator end();

    const_iterator end() const;

    iterator erase(iterator pos);

    iterator find(const Key& key);

    const_iterator find(const Key& key) const;

    class const_iterator;

    class iterator
    {
        QllIterator qllIter;
        OMHash *data;
        friend class const_iterator;
        friend class OrderedMap;

    public:
        iterator() : data(NULL) {}

        iterator(const QllIterator &qllIter, OMHash *data) :
            qllIter(qllIter), data(data) {}

        const Key & key() const
        {
            return *qllIter;
        }

        Value & value() const
        {
            OMHashIterator hit = data->find(*qllIter);
            OMHashValue &pair = hit.value();
            return pair.first;
        }

        Value & operator*() const
        {
            return value();
        }

        iterator operator+(int i) const
        {
            QllIterator q = qllIter;
            q += i;

            return iterator(q, data);
        }

        iterator operator-(int i) const
        {
            return operator +(- i);
        }

        iterator& operator+=(int i)
        {
            qllIter += i;
            return *this;
        }

        iterator& operator-=(int i)
        {
            qllIter -= i;
            return *this;
        }

        iterator& operator++()
        {
            ++qllIter;
            return *this;
        }

        iterator operator++(int)
        {
            iterator it = *this;
            qllIter++;
            return it;
        }

        iterator operator--()
        {
            --qllIter;
            return *this;
        }

        iterator operator--(int)
        {
            iterator it = *this;
            qllIter--;
            return it;
        }

        bool operator ==(const iterator &other) const
        {
            return (qllIter == other.qllIter);
        }

        bool operator !=(const iterator &other) const
        {
            return (qllIter != other.qllIter);
        }
    };

    class const_iterator
    {

        QllConstIterator qllConstIter;
        const OMHash *data;

    public:
        const_iterator() : data(NULL) {}

        const_iterator(const iterator &i) :
            qllConstIter(i.qllIter), data(i.data) {}

        const_iterator(const QllConstIterator &qllConstIter, const OMHash* data) :
            qllConstIter(qllConstIter), data(data) {}

        const Key & key() const
        {
            return *qllConstIter;
        }

        const Value & value() const
        {
            OMHashConstIterator hit = data->find(*qllConstIter);
            const OMHashValue &pair = hit.value();
            return pair.first;
        }

        const Value & operator*() const
        {
            return value();
        }

        const_iterator operator+(int i) const
        {
            QllConstIterator q = qllConstIter;
            q += i;

            return const_iterator(q, data);
        }

        const_iterator operator-(int i) const
        {
            return operator +(- i);
        }

        const_iterator& operator+=(int i)
        {
            qllConstIter += i;
            return *this;
        }

        const_iterator& operator-=(int i)
        {
            qllConstIter -= i;
            return *this;
        }

        const_iterator& operator++()
        {
            ++qllConstIter;
            return *this;
        }

        const_iterator operator++(int)
        {
            const_iterator it = *this;
            qllConstIter++;
            return it;
        }

        const_iterator operator--()
        {
            --qllConstIter;
            return *this;
        }

        const_iterator operator--(int)
        {
            const_iterator it = *this;
            qllConstIter--;
            return it;
        }

        bool operator ==(const const_iterator &other) const
        {
            return (qllConstIter == other.qllConstIter);
        }

        bool operator !=(const const_iterator &other) const
        {
            return (qllConstIter != other.qllConstIter);
        }
    };

private:

    class OMHash : public QHash<Key, OMHashValue >
    {
    public:
        bool operator == (const OMHash &other) const
        {
            if (size() != other.size()) {
                return false;
            }

            if (QHash<Key, OMHashValue >::operator ==(other)) {
                return true;
            }

            typename QHash<Key, OMHashValue >::const_iterator it1 = this->constBegin();
            typename QHash<Key, OMHashValue >::const_iterator it2 = other.constBegin();

            while(it1 != this->end()) {
                OMHashValue v1 = it1.value();
                OMHashValue v2 = it2.value();

                if ((v1.first != v2.first) || !oMHashEqualToKey<Key>(it1.key(), it2.key())) {
                    return false;
                }
                ++it1;
                ++it2;
            }
            return true;
        }
    };

private:
    void copy(const OrderedMap<Key, Value> &other);

    OMHash data;
    QLinkedList<Key> insertOrder;
};

template <typename Key, typename Value>
OrderedMap<Key, Value>::OrderedMap() {}

#ifdef Q_COMPILER_INITIALIZER_LISTS
template<typename Key, typename Value>
OrderedMap<Key, Value>::OrderedMap(std::initializer_list<std::pair<Key, Value> > list)
{
    typedef typename std::initializer_list<std::pair<Key,Value> >::const_iterator const_initlist_iter;
    for (const_initlist_iter it = list.begin(); it != list.end(); ++it)
        insert(it->first, it->second);
}
#endif


template <typename Key, typename Value>
OrderedMap<Key, Value>::OrderedMap(const OrderedMap<Key, Value>& other)
{
    copy(other);
}

#if (QT_VERSION >= 0x050200)
template <typename Key, typename Value>
OrderedMap<Key, Value>::OrderedMap(OrderedMap<Key, Value>&& other)
{
    data = std::move(other.data);
    insertOrder = std::move(other.insertOrder);
}
#endif

template <typename Key, typename Value>
void OrderedMap<Key, Value>::clear()
{
    data.clear();
    insertOrder.clear();
}

template <typename Key, typename Value>
bool OrderedMap<Key, Value>::contains(const Key &key) const
{
    return data.contains(key);
}

template <typename Key, typename Value>
int OrderedMap<Key, Value>::count() const
{
    return data.count();
}

template <typename Key, typename Value>
bool OrderedMap<Key, Value>::empty() const
{
    return data.empty();
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::iterator OrderedMap<Key, Value>::insert(const Key &key, const Value &value)
{
    OMHashIterator it = data.find(key);

    if (it == data.end()) {
        // New key
        QllIterator ioIter = insertOrder.insert(insertOrder.end(), key);
        OMHashValue pair(value, ioIter);
        data.insert(key, pair);
        return iterator(ioIter, &data);
    }

    OMHashValue pair = it.value();
    // remove old reference
    insertOrder.erase(pair.second);
    // Add new reference
    QllIterator ioIter = insertOrder.insert(insertOrder.end(), key);
    pair.first = value;
    pair.second = ioIter;
    data.insert(key, pair);
    return iterator(ioIter, &data);
}

template <typename Key, typename Value>
bool OrderedMap<Key, Value>::isEmpty() const
{
    return data.isEmpty();
}

template<typename Key, typename Value>
QList<Key> OrderedMap<Key, Value>::keys() const
{
    return QList<Key>::fromStdList(insertOrder.toStdList());
}

template<typename Key, typename Value>
int OrderedMap<Key, Value>::remove(const Key &key)
{
    OMHashIterator it = data.find(key);
    if (it == data.end()) {
        return 0;
    }
    OMHashValue pair = it.value();
    insertOrder.erase(pair.second);
    data.erase(it);
    return 1;
}

template<typename Key, typename Value>
int OrderedMap<Key, Value>::size() const
{
    return data.size();
}

template<typename Key, typename Value>
void OrderedMap<Key, Value>::copy(const OrderedMap<Key, Value> &other)
{
    /* Since I'm storing iterators of QLinkedList, I simply cannot make
     * a trivial copy of the linked list. This is a limitation due to implicit
     * sharing used in Qt containers, due to which iterator active on one
     * QLL can change the data of another QLL even after creating a copy.
     *
     * Because of this, the old iterators have to be invalidated and new ones
     * have to be generated.
     */
    insertOrder.clear();
    // Copy hash
    data = other.data;

    QllConstIterator cit = other.insertOrder.begin();
    for (; cit != other.insertOrder.end(); ++cit) {
        Key key = *cit;
        QllIterator ioIter = insertOrder.insert(insertOrder.end(), key);
        OMHashIterator it = data.find(key);
        (*it).second = ioIter;
    }
}

template<typename Key, typename Value>
Value OrderedMap<Key, Value>::take(const Key &key)
{
    OMHashIterator it = data.find(key);
    if (it == data.end()) {
        return Value();
    }
    OMHashValue pair = it.value();
    insertOrder.erase(pair.second);
    data.erase(it);
    return pair.first;
}

template <typename Key, typename Value>
Value OrderedMap<Key, Value>::value(const Key &key) const
{
    return data.value(key).first;
}

template <typename Key, typename Value>
Value OrderedMap<Key, Value>::value(const Key &key, const Value &defaultValue) const
{
    OMHashConstIterator it = data.constFind(key);
    if (it == data.end()) {
        return defaultValue;
    }
    OMHashValue pair = it.value();
    return pair.first;
}

template <typename Key, typename Value>
QList<Value> OrderedMap<Key, Value>::values() const
{
    QList<Value> values;
    foreach (const Key &key, insertOrder.toStdList()) {
        OMHashValue v = data.value(key);
        values.append(v.first);
    }
    return values;
}

template <typename Key, typename Value>
OrderedMap<Key, Value> & OrderedMap<Key, Value>::operator=(const OrderedMap<Key, Value>& other)
{
    if (this != &other) {
        copy(other);
    }
    return *this;
}

#if (QT_VERSION >= 0x050200)
template <typename Key, typename Value>
OrderedMap<Key, Value> & OrderedMap<Key, Value>::operator=(OrderedMap<Key, Value>&& other)
{
    if (this != &other) {
        data = other.data;
        insertOrder = other.insertOrder;
    }
    return *this;
}
#endif

template <typename Key, typename Value>
bool OrderedMap<Key, Value>::operator==(const OrderedMap<Key, Value> &other) const
{
    // 2 Ordered maps are equal if they have the same contents in the same order
    return ((data == other.data) && (insertOrder == other.insertOrder));
}

template <typename Key, typename Value>
bool OrderedMap<Key, Value>::operator!=(const OrderedMap<Key, Value> &other) const
{
    return ((data != other.data) || (insertOrder != other.insertOrder));
}

template <typename Key, typename Value>
Value& OrderedMap<Key, Value>::operator[](const Key &key)
{
    OMHashIterator it = data.find(key);
    if (it == data.end()) {
        insert(key, Value());
        it = data.find(key);
    }
    OMHashValue &pair = it.value();
    return pair.first;
}

template <typename Key, typename Value>
const Value OrderedMap<Key, Value>::operator[](const Key &key) const
{
    return value(key);
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::iterator OrderedMap<Key, Value>::begin()
{
    return iterator(insertOrder.begin(), &data);
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::const_iterator OrderedMap<Key, Value>::begin() const
{
    return const_iterator(insertOrder.begin(), &data);
}


template <typename Key, typename Value>
typename OrderedMap<Key, Value>::iterator OrderedMap<Key, Value>::end()
{
    return iterator(insertOrder.end(), &data);
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::const_iterator OrderedMap<Key, Value>::end() const
{
    return const_iterator(insertOrder.end(), &data);
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::iterator OrderedMap<Key, Value>::erase(iterator pos)
{
    OMHashIterator hit = data.find(*(pos.qllIter));
    if (hit == data.end()) {
        return pos;
    }
    data.erase(hit);
    QllIterator ioIter = insertOrder.erase(pos.qllIter);

    return iterator(ioIter, &data);
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::iterator OrderedMap<Key, Value>::find(const Key& key)
{
    OMHashIterator hit = data.find(key);
    if (hit == data.end()) {
        return end();
    }

    return iterator(hit.value().second, &data);
}

template <typename Key, typename Value>
typename OrderedMap<Key, Value>::const_iterator OrderedMap<Key, Value>::find(const Key& key) const
{
    OMHashConstIterator hit = data.find(key);
    if (hit == data.end()) {
        return end();
    }

    return const_iterator(hit.value().second, &data);
}
#endif // ORDEREDMAP_H

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/572866.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

DDD领域驱动设计总结和C#代码示例

DDD&#xff08;领域驱动设计&#xff09;是一种软件设计方法&#xff0c;它强调以业务领域为核心来驱动软件的设计和开发。 DDD 的设计初衷是为了解决复杂业务领域的设计和开发问题&#xff0c;它提供了一套丰富的概念和模式&#xff0c;帮助开发者更好地理解和建模业务领域&…

【管理咨询宝藏88】556页!公司经营分析内部培训

本报告首发于公号“管理咨询宝藏”&#xff0c;如需阅读完整版报告内容&#xff0c;请查阅公号“管理咨询宝藏”。 【管理咨询宝藏88】556页&#xff01;公司经营分析内部培训 【格式】PDF版本 【关键词】经营分析、内部培训、多业务分析 【核心观点】 - 非常全面和详细的公…

Composer初次接触

php一直都是简单处理一下单片机的后台服务&#xff0c;没什么深入研究 今天安装一个 php composer.phar require qiniu/php-sdkComposer完全不懂&#xff0c;照着一试&#xff0c;就报错了 - topthink/think-installer v1.0.12 requires composer-plugin-api ^1.0 -> found…

Python爬虫入门指南--爬虫技术的由来、发展与未来--实战课程大赠送

爬虫&#xff0c;也称为网络爬虫或网络蜘蛛&#xff0c;是一种自动化程序&#xff0c;专门用于遍历互联网并收集数据。这种技术的起源、发展和未来都与互联网紧密相连&#xff0c;并在信息检索、数据挖掘等多个领域发挥着不可或缺的作用。 "免费IP池大放送&#xff01;助…

【汇编语言】流程转移和子程序

【汇编语言】流程转移和子程序 文章目录 【汇编语言】流程转移和子程序前言一、“转移”综述二、操作符offset三、jmp指令jmp指令——无条件转移jmp指令&#xff1a;依据位移进行转移两种段内转移远转移&#xff1a;jmp far ptr 标号转移地址在寄存器中的jmp指令转移地址在内存…

Linux信号(处理)

个人主页&#xff1a;Lei宝啊 愿所有美好如期而遇 前言&#xff1a; Linux信号(产生)-CSDN博客 Linux信号(保存)-CSDN博客 前面我们解释了信号的产生和保存&#xff0c;接下来我们就要解释信号的处理&#xff0c;关于操作系统在合适的时候对信号进行处理&#xff0c;合适…

C++奇迹之旅:从0开始实现日期时间计算器

文章目录 &#x1f4dd;前言&#x1f320; 头文件Date.h&#x1f309;日期计算函数&#x1f320;前后置&#x1f309;前后置-- &#x1f320;两对象日期相减&#x1f309;自定义流输入和输出 &#x1f309; 代码&#x1f309; 头文件Date.h&#x1f320;Date.cpp&#x1f309; …

(windows ssh) windows开启ssh服务,并通过ssh登录该win主机

☆ 问题描述 想要通过ssh访问win主句 ★ 解决方案 安装ssh服务 打开服务 如果这里开不来就“打开服务”&#xff0c;找到下面两个开启服务 然后可以尝试ssh链接&#xff0c;注意&#xff0c;账号密码&#xff0c;账号是这个&#xff1a; 密码是这个 同理&#xff0c;如果…

matlab新手快速上手5(蚁群算法)

本文根据一个较为简单的蚁群算法框架详细分析蚁群算法的实现过程&#xff0c;对matlab新手友好&#xff0c;源码在文末给出。 蚁群算法简介&#xff1a; 蚁群算法是一种启发式优化算法&#xff0c;灵感来源于观察蚂蚁寻找食物的行为。在这个算法中&#xff0c;解决方案被看作是…

vue3中的ref、isRef、shallowRef、triggerRef和customRef

1.ref 接受一个参数值并返回一个响应式且可改变的 ref 对象。 ref 对象拥有一个指向内部值的单一属性 .value property &#xff0c;指向内部值。 例&#xff1a;此时&#xff0c;页面上的 str1 也跟着变化 <template><div><button click"handleClick&quo…

BUUCTF-MISC-10.LSB1

10.LSB1 题目&#xff1a;lsb隐写&#xff0c;stegsolve可以看到包含了一个PNG图片 使用stegsolve打开这个图片 由PNG文件头可以看出隐写内容为PNG文件&#xff0c;按save Bin键保存为PNG文件。 得到一张二维码图片&#xff0c;使用CQR扫一下

盲返模式:电商领域的新玩法与商业创新

大家好&#xff0c;我是微三云周丽&#xff0c;今天给大家分析当下市场比较火爆的商业模式&#xff01; 小编今天跟大伙们分享什么是什么是盲返模式&#xff1f; 随着互联网的深入发展&#xff0c;电商行业正面临着前所未有的机遇与挑战。在这个竞争激烈的市场环境中&#xff…

GAN 生成对抗神经网络

GAN 文章目录 GANGAN的结构GAN的目标函数GAN的训练GAN的优势和不足优势不足 GAN的结构 GAN的设计灵感来源于博弈论中的零和博弈&#xff08;Zero-sum Game&#xff09;&#xff0c;在零和博弈中&#xff0c;参与双方的收益是完全相反的&#xff0c;一方的收益必然导致另一 方的…

Python400集 视频教程,手把手带你零基础手写神经网络!!

嗨喽&#xff0c;大家好&#xff0c;今天又要给大家整一波福利了&#xff01; 学习编程&#xff0c;最忌讳就是今天一个教程&#xff0c;明天一个教程&#xff0c;频繁更换教程&#xff0c;增加自己的学习成本&#xff0c;对于新手小白会是一件严重打击自信心的事情。所以今天…

jetson开发板+外接散热风扇

本文参考链接 https://news.mydrivers.com/1/580/580811.htm?refhttps%3A//www.baidu.com/link%3Furl%3DM_D45a-od3NK-ER_Flgqqw4LjHLinB1xrmYNj7VVqHlM2zVXwR9Z7FGilCYDRRJYNpIsdejeAfpVtmVTowuFfK%26wd%3D%26eqid%3D81e7865e000256a5000000046628ff4a 一、三种风扇的种类 二…

全自动装箱机多少钱?它的性能和优势又是怎样的呢?

在现代化的生产线中&#xff0c;全自动装箱机已经成为许多企业提升效率、降低成本的重要设备。那么&#xff0c;全自动装箱机到底多少钱?它的性能和优势又是怎样的呢? 一、全自动装箱机&#xff1a;高效省力的生产助手 全自动装箱机是一种高度自动化的包装设备&#xff0c;能…

掌握未来通信技术:5G核心网基础入门

&#x1f525;个人主页&#xff1a;Quitecoder &#x1f525;专栏&#xff1a;5GC笔记仓 朋友们大家好&#xff0c;本篇文章是我们新内容的开始&#xff0c;我们本篇进入5GC的学习&#xff0c;希望大家多多支持&#xff01; 目录 一.核心网的演进2G核心网2.5G核心网3G核心网4G…

CFCASSL证书的网络安全解决方案

在数字化时代&#xff0c;网络信息安全的重要性不言而喻。随着电子商务、在线交易、远程办公等互联网活动的日益普及&#xff0c;确保数据传输的安全性与隐私保护成为企业和用户共同关注的焦点。在此背景下&#xff0c;CFCA SSL证书作为一种权威、高效的网络安全解决方案&#…

ShardingSphere 5.x 系列【24】集成 Nacos 配置中心

有道无术,术尚可求,有术无道,止于术。 本系列Spring Boot 版本 3.1.0 本系列ShardingSphere 版本 5.4.0 源码地址:https://gitee.com/pearl-organization/study-sharding-sphere-demo 文章目录 1. 前言2. ShardingSphereDriverURLProvider3. 方式一:基于 Nacos Java SDK…

《2024年网络弹性风险指数报告》:92%的组织并未准备好应对AI安全挑战

网络弹性是一个比传统网络安全更大、更重要的范例&#xff0c;拥有有效网络弹性能力的组织能在承受网络攻击、技术故障或故意篡改企图后迅速恢复正常业务运营。近日&#xff0c;Absolute security公司发布的《2024年网络弹性风险指数报告》旨在评估当今全球企业的网络弹性状况&…
最新文章