Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QMap::contains() VS QMap::find()

Tags:

c++

qt

qmap

I often see code like:

if(myQMap.contains("my key")){
    myValue = myQMap["my key"];
}

which theoretically performs two look-up's in the QMap.

My first reaction is that it should be replaced by the following, which performs one lookup only and should be two times faster:

auto it = myQMap.find("my key");
if(it != myQMap.end()){
    myValue = it.value();
}

I am wondering if QMap does this optimization automatically for me? In other words, I am wondering if QMap saves the position of the last element found with QMap::contains() and checks it first before performing the next lookup?

like image 578
nbilal Avatar asked Nov 13 '13 21:11

nbilal


2 Answers

I would expect that QMap provides both functions for a better interface to the class. It's more natural to ask if the map 'contains' a value with a specified key than it is to call the 'find' function.

As the code shows, both find and contains call the following internal function: -

Node *n = d->findNode(akey);

So if you're going to use the returned iterator, then using find and checking the return value will be more efficient, but if you just want to know if the value exists in the map, calling contains is better for readability.

If you look at the source code, you'll see that QMap is implemented as a binary tree structure of nodes. Calling findNode iterates through the nodes and does not cache the result.

like image 135
TheDarkKnight Avatar answered Nov 16 '22 13:11

TheDarkKnight


QMap source code reveals that there is no special code in QMap::contains() method.

In some cases you can use QMap::value() or QMap::values() to get value for a key and check if it is correct. These methods (and const operator[]) will copy the value, although this is probably OK for most Qt types since their underlying data are copied-on-write (notably QMap itself).

like image 33
hluk Avatar answered Nov 16 '22 11:11

hluk