Borrimoro
Borrimoro

Reputation: 557

QMap but without sorting by key

I need structure like QMap but without sorting on keys, so if I insert item there first I can count that this item will be before all others. And insert pair before or after specified element. Does Qt have such?

Upvotes: 5

Views: 7556

Answers (3)

Juan
Juan

Reputation: 830

I had the same problem so I'm sharing the solution I used

QMap<QString,int> OldStudentList;
OldStudentList["Dantesc"]     = 8;
OldStudentList["Constantin"]  = 10;
OldStudentList["Abraham"]     = 15;

The "QMap" listing gave this : "Abraham" 15 "Constantin" 10 "Dantesc" 8

Rather than using a QMap I therefore used a structure with a QList of this structure

struct Student
{
  QString name;
  int note;
};

QList<Student> studentList;

Student currentPers;

currentPers.name = "Dantesc";
currentPers.note = 8;
studentList.append(currentPers);

currentPers.name = "Constantin";
currentPers.note = 10;
studentList.append(currentPers);

currentPers.name = "Abraham";
currentPers.note = 15;
studentList.append(currentPers);

for(int i=0;i<studentList.size();i++){ qDebug() << studentList[i].name << studentList[i].note; }

This listing give this : "Dantesc" 8 "Constantin" 10 "Abraham" 15
I keep the order of the data entered

Hope this solution can help someone

Upvotes: 0

Komgcn
Komgcn

Reputation: 355

I use a

QList<QPair<key,value>> 

to achieve this. But look up consumes more time as you will need to loop through the QList and use the QPair.first to look for the item you want.

edit: if you dont need it to interact with other API alot, you can use QVector to replace QList which is faster according to Qt official

Upvotes: 2

Jan Kundr&#225;t
Jan Kundr&#225;t

Reputation: 3816

QMap is implemented as a tree, which means that the insertion order does not matter. It appears that you are looking for a queue. However, if you need a container which can be iterated in both insertion order and at the same time accessed through a specific key, then Qt has no such structure for you.

These could help you:

Upvotes: 3

Related Questions