Home > Enterprise >  Is there a map-like tool in QT that can be iterated over inserted index?
Is there a map-like tool in QT that can be iterated over inserted index?

Time:09-30

From the Qt documentation about QMap::iterator :

Unlike QHash, which stores its items in an arbitrary order, QMap stores its items ordered by key. Items that share the same key (because they were inserted using QMap::insertMulti(), or due to a unite()) will appear consecutively, from the most recently to the least recently inserted value.

What I want is to interate a map by inserted index. For example this map.

const static QMap<QString, int> MEASUREMENT_COLUMNS{{"ID", MY_SQL_BIGINT}, {"logging_id", MY_SQL_INT}, {"calibration_id", MY_SQL_INT}, {"logging_comment", MY_SQL_VARCHAR255}, {"measurement_date_time", MY_SQL_DATETIME}, {"ADC0", MY_SQL_FLOAT},
                                                    {"ADC0", MY_SQL_FLOAT},
                                                    {"ADC1", MY_SQL_FLOAT},
                                                    {"ADC2", MY_SQL_FLOAT},

But the problem is as the documentation says above about QMap and QHashmap. They will not work for be if I want to iterate a map by inserted index.

For example, first ID, then logging_id, then calibration_id etc. So I need to select something else than QMap and QHash.

Question:

Is there a map-like tool in QT that can be iterated over inserted index?

CodePudding user response:

You can use two QVector, or use QVector<QPair<QString, int> > instead.

CodePudding user response:

Not in QT (to my knowledge, at least). Can you use Boost, e.g. boost::multiindex? Another option is to combine map with vector in a class - like this (this is likely to contain errors; it's supposed to illustrate the general idea, not to be a fully working piece of code):

template<typename K, typename V>
class indexed_map
{
  map<K, V> m_map;
  vector<K> m_insertionOrder;
public:
  void insert(const K& k, const V& v)
  {
    m_map.insert(k,v);
    m_insertionOrder.push_back(k);
  }

  V byKey(const K& k) const {return m_map.at(k)};
  V byOrder(size_t n) const {return m_map.at(m_insertionOrder.at(n));}
};

Of course you'll have to write some boilerplate (ok, lots of it in fact), iterators might be also tricky.

  • Related