Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QMap and QPair, C++, Qt

I want to make a data structure for accessing strings by two ways:

  1. Access by ID
  2. Access by name

My first idea is using two maps for each method but it leads to duplication of data:

QMap<int, QString> accessById;
QMap<QString, QString> accessByName;

I'm searching for a better way, something like this:

QMap<QPair<int, QString>, QString> multiAccess;

but it can not help me (at least I don't know how to do it), because searching in a map needs to know ID and name together. How can I define a well structure of Qt classes to achive my goal?

No external libraries, but Qt

like image 504
masoud Avatar asked Oct 04 '11 09:10

masoud


2 Answers

How about:

QMap<QString, int> nameIdMap;
QMap<int, QString> accessById;

You access by id and create a map for names and ids. Then you can access by name with

QString data = accessById[nameIdMap[the_name]];
like image 159
Juho Avatar answered Sep 28 '22 07:09

Juho


Qt doesn't have as much worry about duplication of data as many other class libraries do, because of "implicit sharing":

http://doc.qt.nokia.com/latest/implicit-sharing.html

The list of classes which have this property (which include QString) is covered in that link. There are helpers to create your own classes which use a Copy-On-Write strategy as well:

http://en.wikipedia.org/wiki/Copy-on-write

http://doc.qt.nokia.com/latest/qshareddatapointer.html#details

To summarize: if you have a 10,000-character QString and assign it to another QString variable, you will not pay for another 10,000 characters of storage (unless you modify the string data of one of the two instances). Still, even a read-only QString handle is a bit bigger than an int. It depends on your scenario whether that size difference is significant vs. the speed tradeoff of multiple lookups, as in the strategy offered by @Juho.

like image 43
HostileFork says dont trust SE Avatar answered Sep 28 '22 05:09

HostileFork says dont trust SE