简体   繁体   English

QMap和QPair,C ++,Qt

[英]QMap and QPair, C++, Qt

I want to make a data structure for accessing strings by two ways: 我想通过两种方式创建一个用于访问字符串的数据结构:

  1. Access by ID 按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. 但它无法帮助我(至少我不知道该怎么做),因为在地图中搜索需要知道ID和名称。 How can I define a well structure of Qt classes to achive my goal? 如何定义Qt类的井结构以实现我的目标?

No external libraries, but Qt 没有外部库,但Qt

How about: 怎么样:

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

You access by id and create a map for names and ids. 您可以通过id访问并为名称和ID创建地图。 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": 由于“隐式共享”,Qt没有像许多其他类库那样担心重复数据:

http://doc.qt.nokia.com/latest/implicit-sharing.html 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. 具有此属性的类列表(包括QString )包含在该链接中。 There are helpers to create your own classes which use a Copy-On-Write strategy as well: 有助手可以创建自己的类,这些类也使用Copy-On-Write策略:

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

http://doc.qt.nokia.com/latest/qshareddatapointer.html#details 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). 总结一下:如果你有一个10,000字符的QString并将其分配给另一个QString变量,你将不会支付另外10,000个字符的存储空间(除非你修改两个实例之一的字符串数据)。 Still, even a read-only QString handle is a bit bigger than an int . 尽管如此,即使是只读的QString句柄也比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. 这取决于您的场景,这种大小差异是否显着与多次查找的速度权衡相比,如@Juho提供的策略。

您可以使用Boost Bimap ,它将在id和Name之间创建双向映射。

boost::bimap<int, QString> idNameBimap;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM