lundi 23 avril 2018

How to use C++11 range-based for with QJsonArray

With old-style loops, I can delve into a QJsonArray and, in the example below, add element "foo" with contents of existing element "bar" for each array item. How can I do this using C++11 range-based for?

// QJsonArray oldArray contains an array of which one element is "bar"
QJsonArray newArray;
int i, b = oldArray.count();
for (i=0; i<n; ++i) {
    QJsonObject element = oldArray.at(i).toObject();
    element["foo"] = element["bar"];
    newArray.append(element);
}

I have tried the following (admittedly as trial and error):

auto&

for (auto& element : oldArray) {
    element["foo"] = element["bar];
    newArray.append(element);
}

I get the error

non-const lvalue reference to type 'QJsonValueRef' cannot bind to a temporary of type 'QJsonValueRef'

const auto&

for (const auto& element : oldArray) {
...

I get a warning

loop variable 'element' is always a copy because the range of type 'QJsonArray' does not return a reference

const auto

for (const auto element : oldArray) {
    element["foo"] = element["bar];
    ...

I get the error

no viable overloaded operator[] for type 'const QJsonValueRef'

relating to element["bar"]

Aucun commentaire:

Enregistrer un commentaire