【问题标题】:QT container, with specified order and no repetitionsQT 容器,指定顺序且无重复
【发布时间】:2017-01-08 09:33:51
【问题描述】:

我需要类似于 QSet 的东西,但我需要按照插入的顺序保存项目

有这种事吗?

【问题讨论】:

  • 没有足够的信息来响应:你使用什么类型的项目,你想如何插入和访问它们......它可以是任何下一个容器:QMapQHashQVectorQList 等...见Qt Container Classes
  • @VladimirBershov - 你提到的容器要么重复,要么不按我插入的顺序保存项目。
  • 为什么不直接使用QVector::append()insert()
  • 因为我不想重复(而且我不想在每次添加新值时手动检查该值是否存在)

标签: qt containers qset


【解决方案1】:

我不知道在 Qt 和 STL 中开箱即用的东西。我认为 Boost 有类似的东西,但自己做这件事并不难。

您可以像这样对QHash 进行包装:

template<typename T>
class MySet : QHash<T, int>
{
public:
    using QHash<T, int>::QHash;

    QVector<T> values() //this 'hides' the base QHash::values() of QHash
    {
        QVector<T> vec(count());

        for(auto it = cbegin(); it != end(); ++it)
        {
            vec[it.value()] = it.key();
        }

        return vec;
    }

    void insert(const T &value)
    {
        if(!contains(value))
        {
            insert(value, m_Data.count());
        }
    }
};

用法和QSet很相似:

MySet<QString> set;
set.insert("1");
set.insert("2");
set.insert("3");
qDebug() << set.values();

然后按顺序打印值。如果您需要更多 complete 支持,例如迭代器也以您想要的顺序进行迭代,您将不得不重新实现更多功能,但其要点是相同的。毕竟QSet 在内部也是QHash。注意以上不支持不修改就删除。

【讨论】:

    【解决方案2】:

    也许 QList 或 QVector 会有所帮助。

    QList<QString> stringList;
    //By the way, Qt provides QStringList as a typedef for QList<QString>
    stringList.append("A");
    stringList.append("B");
    
    qDebug() << stringList.at(0); //A
    qDebug() << stringList.at(1); //B
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 2015-08-28
      相关资源
      最近更新 更多