开发者

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


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]];


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.


You could use Boost Bimap which will create a bidirectional map between the id and Name.

boost::bimap<int, QString> idNameBimap;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜