[英]Reallocate a std::vector of struct
假設我們有一個struct
s的std::vector
:
struct abc {
wstring a; // length between 0 and 200, 100 on average
long b;
long c;
};
std::vector<abc> v; // 1 - 10 millions of items will be there
在重新分配的情況下會發生什么(例如,因為push_back()
時容量太小,或者我自己突然用v.reserve(v.size() + 100000
)增加了容量)?
更精確地:
wstrings
都被重寫,等等) 要么
?
為了使問題更清楚,它看起來像這樣嗎
或像這樣:
或這一個:
還是另一種方式?
其他信息,以供將來參考:
struct abc { wstring a; int b; int c; };
wcout << sizeof(wstring); // 32
wcout << sizeof(int); // 4
wcout << sizeof(abc); // 40, so this means there's probably no extra byte
// used by the "struct" envelope itself
wcout << sizeof(tuple<wstring, int, int>); // 40 too
std::vector
存儲abc
對象,而不是指向它們的指針。 在C ++ 11之前,將向量的容量擴展到超出已分配的容量(可能大於向量的大小)之前,需要將實際對象復制到新分配的數組中。
從C ++ 11開始,引入了MoveInsertable
概念。 現在,數據已從舊位置移動到新位置,這在重新分配和CPU周期方面可能會便宜得多。 特別是, abc
內的wstring
不需要復制字符串本身的內容,這可能會節省很多錢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.