0

#include <iostream>
#include <map>
#include <unordered_map>

#include <QHash>
#include <QMap>
#include <QString>

void _QMap()
{
    QMap<int, QString> amap;

    amap.insert(2, "cdasdc");
    amap.insert(1, "cda");
    amap.insert(3, "zzz");

    std::cout << std::endl;
    auto i = amap.begin();
    while (i != amap.end())
        std::cout << i.key() << " " << i++.value().toStdString() << std::endl;

}

void _map()
{
    std::map<int, std::string> bmap;

    std::pair<int, std::string> val(2, "cdasdc");
    bmap.insert({1, "cda"});
    bmap.insert({3, "zzz"});
    bmap.insert(val);

    std::cout << std::endl;
    for (auto& i :  bmap)
        std::cout << i.first << " "<< i.second << std::endl;

}

void _QHash()
{
    QHash<int, QString> ahash;

    ahash.insert(2, "cdasdc");
    ahash.insert(1, "cd");
    ahash.insert(3, "zzz");

    std::cout << std::endl;
    auto i = ahash.begin();
    while (i != ahash.end())
        std::cout << i.key() << " " << i++.value().toStdString() << std::endl;
}

void _hash()
{
    std::unordered_map<int, std::string> ahash;

    ahash.insert({2, "cdasdc"});
    ahash.insert({1, "cd"});
    ahash.insert({3, "zzz"});

    std::cout << std::endl;
    for (auto& i :  ahash)
        std::cout << i.first << " "<< i.second << std::endl;
}

int main()
{
    _QMap();

    _map();

    _QHash();

    _hash();
}

I run above code multiple times and observed the output. The _QHash() print is different each time, which I was expecting since documentation says the items are arbitrarily ordered.

I was expecting QHash and std::unordered_map to behave the same way since documentation says the elements are not sorted.

However _hash() print is always the same. Why?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • 1
    Ask yourself, how is 'the elements print in the same order each time' incompatible with 'the elements are not sorted'? I think you are reading more into the documentation than is warranted. – john Feb 19 '23 at 11:32

1 Answers1

0

see https://doc.qt.io/qt-6/qhash.html#algorithmic-complexity-attacks

"In order to avoid this worst-case behavior, the calculation of the hash value done by qHash() can be salted by a random seed, that nullifies the attack's extent. This seed is automatically generated by QHash once per process, and then passed by QHash as the second argument of the two-arguments overload of the qHash() function.

David
  • 26
  • 2