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;
}