I have the following code for doing a http post request. I am getting the response in
const std::vector<json> value
...The below code works correctly
RpcResponseAndContext<std::vector<Largest>>
Connection::getLargestAccounts() const {
const json params = {};
const auto reqJson = jsonRequest("getLargest", params);
const json res = sendJsonRpcRequest(reqJson);
const std::vector<json> value = res["value"];
std::vector<Largest> accounts_list;
accounts_list.reserve(value.size());
for (const json &account : value) {
accounts_list.push_back(account);
}
return {res["context"], accounts_list};
}
To improve the appending of elements into accounts_list
vector..I am trying to use std::copy()
But getting this error: FATAL ERROR: test case CRASHED: SIGSEGV - Segmentation violation signal
I am trying this way:
RpcResponseAndContext<std::vector<Largest>>
Connection::getLargestAccounts() const {
const json params = {};
const auto reqJson = jsonRequest("getLargest", params);
const json res = sendJsonRpcRequest(reqJson);
const std::vector<json> value = res["value"];
std::vector<Largest> accounts_list;
accounts_list.reserve(value.size());
std::copy(value.begin(), value.end(), accounts_list.begin());
return {res["context"], accounts_list};
}
What I am doing wrong ?
CodePudding user response:
reserve
does not resize
the vector, it just pre-allocates the space so push_back
s are cheap and never invalidate any iterators but they are still required.
std::copy
assumes (like most <algorithm>
s) the output iterators are valid, i.e. point to existing location. In this case they do not.
What you need is std::back_inserter
which will call push_back
for you:
accounts_list.reserve(value.size()); // Optional optimization
std::copy(value.begin(), value.end(), std::back_inserter(accounts_list));
I am not actually sure whether this is the cause since you did not provide a minimal reproducible example, I would expect some iterator assertion, not segfault since the memory should have been allocated. Maybe some empty std::vector
optimization is at play.