我有以下代碼用于執行 http 發布請求。我得到了回應
const std::vector<json> value......下面的代碼可以正常作業
Ttran<std::vector<Lar>> get() const {
const std::vector<json> value = res["value"];
std::vector<Lar> account;
for (const json &account : value) {
account.push_back(account);
}
return {res["context"], accounts};
}
為了改進將元素附加到accounts向量中..我正在嘗試使用 std::copy() 但收到此錯誤:致命錯誤:測驗用例崩潰:SIGSEGV - 分段違規信號
我正在嘗試這種方式:
Ttran<std::vector<Lar>> get() const {
const std::vector<json> value = res["value"];
std::vector<Lar> accounts;
std::copy(value.begin(), value.end(), accounts.begin());
return {res["context"], accounts};
}
我做錯了什么?
uj5u.com熱心網友回復:
reserve不是resize向量,它只是預先分配空間,所以push_backs 很便宜并且永遠不會使任何迭代器無效,但它們仍然是必需的。
std::copy假設(像大多數<algorithm>s)輸出迭代器是有效的,即指向現有位置。在這種情況下,他們沒有。
你需要的是std::back_inserter哪個會召喚push_back你:
accounts_list.reserve(value.size()); // Optional optimization
std::copy(value.begin(), value.end(), std::back_inserter(accounts_list));
我實際上不確定這是否是原因,因為您沒有提供最小的可重現示例,我希望有一些迭代器斷言,而不是段錯誤,因為應該分配記憶體。也許一些空洞std::vector的優化正在發揮作用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532661.html
上一篇:CAS操作的記憶體屏障使用情況
