c++qtcontainersinitializer-listqhash

Initializing const QHash by joining with an existing QHash


In my project I need several constant hash-containers which are defined outside classes and functions and so are global. With that, some of these containers should overlap. With lists I would do the following to combine second const list with the first const list:

const QList<QString> data1({
     "one",
     "two",
     "three"
 });

const QList<QString> data2 =
     data1 + 
     QList<QString>({
        "four",
        "five"
     });

But this doesn't work with QHashes, as there is no + operator for them. Instead, they have unite member function, but I cannot use it since containers are const. So what I want is something like this:

const QHash<QString,int> hash1{
    {"one", 1},
    {"two", 2},
    {"three", 3}
};

const QHash<QString,int> hash2 = 
    hash1 +
    QHash<QString,int>({
    {"four", 4},
    {"five", 5}
});

or

const QHash<QString,int> hash2({
    {"four", 4},
    {"five", 5}
}).unite(hash1);

Solution

  • const QHash<QString,int> hash2 = QHash<QString,int>{
        {"four", 4},
        {"five", 5}
    }.unite(hash1);
    

    Bit shorter

    const auto hash2 = QHash<QString,int>{
        {"four", 4},
        {"five", 5}
    }.unite(hash1);
    

    If you remember how operator+ is expanded then you will understand that call of unite or call of operator+ are grammatically the same.

    const QList<QString> data2 =
         data1.operator+(
         QList<QString>({
            "four",
            "five"
         }));