std::transform over QMap
-
@Venkateswaran said in std::transform over QMap:
std::back_inserter(map2)
How should this work? QMap has no push_back() and can't have it since it needs a key and a value.
-
@Christian-Ehrlicher is there any other way to achieve this without general for loop?
-
No, but why?
for (auto it = map.begin(); it != map.end(); ++i) map2.insert(it.key + "testing", it.value);
-
@Christian-Ehrlicher Because of cppcheck in my project :) it's not allowing me to use for loop for this.
-
@Venkateswaran said in std::transform over QMap:
it's not allowing me to use for loop for this
?
Can you post what it tells you? -
@Venkateswaran said in std::transform over QMap:
it's not allowing me to use for loop for this.
It's just suggesting to use std functions when possible. But it is not. Blame cppcheck.
-
I guess the correct code could would look like
void fun() { QMap<QString, int> map; QMap<QString, int> map2; std::transform(map.begin(), map.end(), std::inserter(map2, map2.end()), [](auto &todo) { return todo; }); }
however there seems to be no
QMap<QString, int>::value_type
defined. Qts container seem do not stick to the standard, so thestd::inserter
paradigma does not work.using the standard map, it compiles.
void works() { std::map<QString, int> map; std::map<QString, int> map2; std::transform(map.begin(), map.end(), std::inserter(map2, map2.end()), [](auto &todo) { return todo; }); }
Have fun
Markus -
@qwertzui11 said in std::transform over QMap:
Qts container seem do not stick to the standard,
correct because QMap was there earlier :)
A range-based for-loop for QMap similar to std::map can be done with https://doc.qt.io/qt-5/qmap-key-iterator.html afair
-
Ok. My actual conversion is from QMap<quint16, QPair<QString, quint16>> to QMap<quint16, QPair<QUuid, quint16>> and QHash<QString, int> to QHash<QUuid, int>
QMap<quint16, QPair<QUuid, quint16>> map2; for(auto it = map.begin(); it != map.end(); ++it) map2.insert(it.key(), qMakePair(QUuid(it.value().first), it.value().second));
QHash<QUuid, int>map2; for(auto it = map.begin(); it != map.end(); ++it) map2.insert(QUuid(it.key()), it.value());
and the cppCheck not complaining. Looks like cppcheck complain only if didn't do much inside the loop (I'm not sure).
I get the below warning when I convert QList<enum> to QList<QString>.
Controller.cpp:120:21: warning: Consider using std::transform algorithm instead of a raw loop. [useStlAlgorithm] versionsInStr.push_back(convertApiVersionToString(ver));
Thank you @Christian-Ehrlicher
-
@Christian-Ehrlicher agreed. I hope Qt6 fixes these smalls gaps :-)
-
@qwertzui11 It can't since it will break a lot of existing stuff - you won't explain all customers that the range-based for loop for containers now returns an iterator instead the value on a QMap and that they have to adjust all of it's code. :(
-
Hi,
You can use QMap:: keyValueBegin and QMap::keyValueEnd for your use case.