[英]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.