简体   繁体   中英

QMap vs QList Class in the Qt framework

I'm trying to decide on whether to use the QList or QMap class in some of my future Qt projects. In order to determine the best choice for me, I'd like to determine some of their similarities and some of their differences in order to understand what works best in certain instances. Is my understanding of these similarities and differences correct?

Similarities:

  • Both are containers

  • Both contain unordered data

Differences:

  • QMap has key value pairs whilst QList only has values

  • QMap uses a hash function to place values in the appropriate index whilst QList simply appends the entries

Are there any more items of similarities and differences?

I could look at the generic computer science definitions but I read somewhere there could be nuanced differences in the Qt framework.

QList and QMap differ in the way the data is being organized. This results in different performance and slightly different memory consumption (for most use cases the latter usually doesn't matter). You can find the computational complexity in the Qt documentation . If you are storing a lot of elements this might make a big difference. Think about how frequently you want to access the data when selecting a container (searching vs. inserting vs. deleting).

[Keep in mind, though, that algorithmic complexity is a theoretical property that is only useful for large n. In practice a linear search through an array with a small number of elements (<1,000) often outperforms lists/trees due to locality of reference . If you care about performance don't guess, always measure.]

Both contain unordered data

That's actually not true for QMap . QMap is implemented as a self-balancing binary search tree which is a sorted data structure.

BTW: You can often implement your code in a generic way that makes it easy to switch to another container type later (eg if the access pattern changes or your assumptions turn out to be wrong). Using auto can help making this painless.

I think you made some mistakes about QMap .

The QMap keeps its content always sorted by key. See the Documentation here . So it is not unordered as you mentioned.

Then a QMap does not use a hash function. It stores elements by comparing them with operator<() .

In fact, you a confusing QMap and QHash . The QHash is indeed arbitrarily ordered and its elements needs to provide an operator==() for the comparison and a qHash(key) function.

I think it can help you to better understand what you need to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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