简体   繁体   中英

Fastest way to convert Vector to QJsonArray?

Currently, I am iterating through a vector in order to convert it to a QJsonArray:

QJsonArray toJson(const std::vector<unsigned short>& myVec) {
    QJsonArray result;
    for(auto i = myVec.begin(); i != myVec.end(); i++) {
        result.push_back((*i));
    }
    return result;
}

However, this causes a small lag spike in my program. Is there an alternative method to receive a QJsonArray with the data from a vector? (It doesn't need to be a deep copy.)

I am afraid there is no faster way than the one you designed. QJsonArray consists of QJsonValue values, that can encapsulate native values of different types: Null , Bool , Double , String , ..., Undefined . But std::vector consists of values of one only type. Therefore each value of a vector should be converted to QJsonValue individually, and there is no faster way like memcopy .

In any case you may shorten your function.

QJsonArray toJson(const std::vector<unsigned short>& myVec) {
    QJsonArray result;
    std::copy (myVec.begin(), myVec.end(), std::back_inserter(result));
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM