3

I need somthing similar to QSet, but I need the items to be saved on the order I inserted them

is there such thing?

kakush
  • 3,334
  • 14
  • 47
  • 68
  • Not enough information for response: what types of items do you use, how do you want to insert and access them... It can be any of the next containers: [QMap](http://doc.qt.io/qt-5/qmap.html), [QHash](http://doc.qt.io/qt-5/qhash.html#qhash), [QVector](http://doc.qt.io/qt-5/qvector.html), [QList](http://doc.qt.io/qt-5/qlist.html), etc... See [Qt Container Classes](http://doc.qt.io/qt-5/containers.html) – Vladimir Bershov Jan 08 '17 at 10:43
  • @VladimirBershov - the containers you mentioned are either with repetitions or don't save items by the order I inserted them. – kakush Jan 09 '17 at 07:45
  • Why not simply [QVector::append()](http://doc.qt.io/qt-5/qvector.html#append) or [insert()](http://doc.qt.io/qt-5/qvector.html#insert)? – Vladimir Bershov Jan 09 '17 at 08:01
  • because I don't want duplicates (and I don't want to manually to check if the value exists every time I want to add a new value) – kakush Jan 09 '17 at 12:26

2 Answers2

4

I am not aware of anything like that out of the box in neither Qt nor STL. Boost has something like that I think but it is not that hard to do this yourself.

You could do a wrapper around QHash like this:

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());
        }
    }
};

The usage is quite similar to QSet:

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

And that prints the values in order. If you need more complete support like iterators also iterating in your desired order you would have to reimplement more functionality but the gist of it would be the same. After all QSet is internally QHash as well. Note that the above does not support removal without modification.

Resurrection
  • 3,916
  • 2
  • 34
  • 56
-1

Maybe a QList or a QVector could help.

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
Victor Tran
  • 516
  • 4
  • 16