[Development] QList

Marc Mutz marc.mutz at kdab.com
Mon Mar 20 18:40:59 CET 2017


Hi other-Mark,

On Monday 20 March 2017 17:14:30 Mark Gaiser wrote:
> I'm fine with replacing QList usages with QVector in codebases i
> maintain, but even with the latest Qt version, that isn't always
> possible or convenient.
> For instance, at this very moment i want a QVector with all keys from
> a given map (QMap<QDate, QString>) but Qt itself doesn't provide a
> direct way of doing that.

What's a "direct way"? Don't assume there's a member function for everything 
you'd ever want to do with a container. Such folly has led to QList::toSet(), 
which, in turn has led to

   // needed for QList::toSet() to compile
   uint qHash(const QItemSelectionRange &, uint = 0) { return 0; }

> The keys method on the map returns a QList.
> QList has a "toVector" method which gives me the QVector i want.
> 
> It works, yes. But it's really indirect.

  template <typename Key, typename V>
  QVector<Key> keys(const QHash<Key, V> &hash) {
      QVector<Key> result;
      result.reserve(hash.size());
      for (auto it = hash.begin(), end = hash.end(), it != end; ++it)
          result.append(it.key());
      return result;
  }
  // ... same for QMap ...
  template <typename Key, typename...Args>
  QVector<Key> keys(const std::unordered_map<Key, Args...> &hash) {
      QVector<Key> result;
      result.reserve(hash.size());
      for (const auto &p : hash)
          result.append(p.first);
      return result;
  }

You write these functions once, put them in your util.h, and are done with it. 
It's the same for STL: 
https://github.com/KDE/libkleo/blob/2fe48b77ba61fada80eaace8cb71dd0fd13265ae/src/kleo/stl_util.h

That file evolved through half a dozen projects.

> The key kinda has to be unique in a map (and hash) so it would be
> perfectly fine for it to be a QVector, but it isn't.
> Is there a technical reason for it or is it just because of Qt's history?

Just because of Qt's history of preferring QList for everything.

Thanks,
Marc

-- 
Marc Mutz <marc.mutz at kdab.com> | Senior Software Engineer
KDAB (Deutschland) GmbH & Co.KG, a KDAB Group Company
Tel: +49-30-521325470
KDAB - The Qt, C++ and OpenGL Experts



More information about the Development mailing list