我有一个随机生成的整数列表,并用这些值填充了一个QMap,但我希望获得按值排序的QMap
发布于 2012-11-20 14:45:20
这是一个演示如何在qt C++中按值而不是按键对QMap <int, int>进行排序。
QMap的值被提取并存储在QList容器对象中,然后通过qSort方法进行排序。密钥本身也存储在QList中。排序完成后,然后清除QMap对象,然后按值的升序将键和值插入回QMap容器中。请参阅下面的解决方案:
#include <QCoreApplication>
#include <qalgorithms.h>
#include <QMap>
#include <QDebug>
#include <QList>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMap <int, int> dataMapList;
//QMap <int, int> sorted = new QMap<int, int>();
QList <int> keys; // container to store all keys from QMap container
QList<int> values; // container to store all values from QMap container
QMap<int, int>::Iterator h; // used to loop/ iterate through QMap
// used to iterate through QLists
QList<int>::Iterator i; //
QList<int>::Iterator j;
//inserts to QMap Container
dataMapList.insert(1,34);
dataMapList.insert(3,2);
dataMapList.insert(2,32);
dataMapList.insert(14,89);
dataMapList.insert(7,23);
h=dataMapList.begin();
qDebug()<< "unsorted";
//list out the unsorted values along with their respective keys
while(h!=dataMapList.end()){
qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl;
h++;
}
values = dataMapList.values(); // pass all values in the QMap to a QList container to store values only
keys= dataMapList.keys(); // pass all keys in the QMap to a QList container to store already sorted by default keys
qSort(values); // sorts the values in ascending order
dataMapList.clear(); // empties the QMap
i=values.begin();
j=keys.begin();
// insert back the sorted values and map them to keys in QMap container
while(i!=values.end() && j!=keys.end()){
dataMapList.insert(*j, *i);
i++;
j++;
}
qDebug() << "sorted" << endl;
h=dataMapList.begin();
//the display of the sorted QMap
while(h!=dataMapList.end()){
qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl;
h++;
}
return a.exec();
}注意: QMap和QList的迭代器用于遍历容器以访问存储的值和/或键。这些也有助于显示列表中的项目(未排序和已排序)。这个解决方案是在Qt控制台应用程序中完成的。
发布于 2012-11-20 08:07:04
在QMap中,默认情况下,项始终按键排序。所以,如果你像这样遍历QMap:
QMap<int, int>::const_iterator i = yourQMap.constBegin();
while (i != yourQMap.constEnd()) {
cout << i.key() << ": " << i.value() << endl;
++i;
}您将获得按键排序的结果。
试着把你的任务转换成适合标准算法的。否则,您可以使用此方法对您的标题进行排序:
QList<int> list = yourQMap.values();
qSort(list.begin(), list.end());然后,如果需要的话,可以通过调用QMap::key(const T &value);方法来获取相关的键。
发布于 2014-03-13 05:45:42
根据具体情况,另一种替代方法是简单地交换键和值,因为键将由QMap自动排序。在大多数情况下,这些值不是唯一的,因此只需使用QMultiMap即可。
例如,假设我们在QMap中有以下数据:
Key Value
--- -----
1 100
2 87
3 430
4 87下面的代码将按值对数据进行排序。
QMap<int, int> oldMap;
QMultiMap<int, int> newMap;
QMapIterator<int, int> it(oldMap);
while (it.hasNext())
{
it.next();
newMap.insertMulti(it.value(), it.key()); //swap value and key
}我们的新地图现在看起来像这样:
Key Value
--- -----
87 4
87 2
100 1
430 3https://stackoverflow.com/questions/13463698
复制相似问题