wazza
wazza

Reputation: 317

QHash of QPair iteration

QHash<QPair<QString N_id, QString A_id>, QString name> info

I have this QHash , and i have the values of N_id and name for a particular index, how can i obtain the value of corresponding A_id. I am trying to use STL-style iterator. I can change QHash to QMap if needed but I cannot use:

QHash<QPair<QString N_id, QString name>, QString A_id>

Edit: N_id and A_id together forms a unique key in my case.

Upvotes: 1

Views: 2452

Answers (1)

iksemyonov
iksemyonov

Reputation: 4196

I think the major problem here is that QHash, being a hash table, looks up the values by hashing the keys. Hence, it needs to complete key to be able to look up a value; a "partial" key won't suffice - there's going to be no concrete object to hash then. A similar problem arises with a map: to navigate the BST, you need the complete object in order to make comparisons and left / right decisions. Thus, short of going back to the drawing board and revising your approach, I'd say, maintain a backwards map, be it a QHash or a QMap, with the mapping name -> pair(n_id, a_id). The downside is that you're going to have to keep the two in sync.

However, with the existing data structure, I'd perform a query like this:

#include <algorithm>

QHash<QPair<QString, QString>, QString> info;
QString a_n_id {/*...*/}; // the target N_id
QString a_name {/*...*/}; // the target name
/* ... */
const auto keyList = info.keys(a_name); // QList<QPair<QString, QString> >
std::find_if(keyList.begin(), keyList.end(),
             [&](decltype(info)::key_type& key) { return key.first == a_n_id; });

See this question in case decltype(info)::value_type refuses to build on Microsoft VS.

This is of course going to be linear, since, as I've already said, a hash needs the complete object to be able to perform a lookup, hence we can't use the logarithmic complexity lookup in this case.

Upvotes: 2

Related Questions