0

I have a QVariantMap, which is an alias for QMap<QString, QVariant>. And I have a function which takes QStringView key as argument. I want to search a value in the map by the key.

QVariantMap map;
QStringView key;
QVariant v = map.value(key);

But the third line does not compile. Of course I could convert the string view to QString but this means one extra memory allocation. Is there any way around this which avoids the unnecessary allocation? How to lookup the value by just the string view?

  • Not sure about QT but this is possible in the standard C++ library from C++14. See [transparent comparators](https://stackoverflow.com/questions/20317413/what-are-transparent-comparators) – john Aug 19 '22 at 16:47

1 Answers1

0

there is no other solution ,

  1. change the keys type to QStringView or
  2. QVariant v = map.value(key.toString());
  • 1
    Well, QStringView as a QMap key would not work very well, IMO, since the underlying string would probably be deleted sooner or later while the map would still exist... So it seems there is only solution. I am tempted to report this as a performance bug / improvement to Qt. Maybe they could somehow specialize templates which take QString as key also for QStringView... – HiFile.app - best file manager Aug 19 '22 at 17:38