[英]Reallocate a std::vector of struct
Let's say we have a std::vector
of struct
s: 假设我们有一个
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
What happens in case of a reallocation (for example because capacity is too small when push_back()
, or if I suddenly increase the capacity myself with v.reserve(v.size() + 100000
)? 在重新分配的情况下会发生什么(例如,因为
push_back()
时容量太小,或者我自己突然用v.reserve(v.size() + 100000
)增加了容量)?
More precsily: 更精确地:
wstrings
are all rewritten, etc.) wstrings
都被重写,等等) or 要么
? ?
To make the question clearer, does it look like this 为了使问题更清楚,它看起来像这样吗
or like this: 或像这样:
or this one: 或这一个:
or another way? 还是另一种方式?
Additional informations for future reference: 其他信息,以供将来参考:
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
stores abc
objects, not pointers to them. std::vector
存储abc
对象,而不是指向它们的指针。 Prior to C++11 expanding the capacity of the vector beyond what has been allocated (which may be greater than vector's size) would require copying the actual objects into the newly allocated array. 在C ++ 11之前,将向量的容量扩展到超出已分配的容量(可能大于向量的大小)之前,需要将实际对象复制到新分配的数组中。
Starting with C++11 MoveInsertable
concept has been introduced. 从C ++ 11开始,引入了
MoveInsertable
概念。 Now the data is moved from the old location to the new location, which may be significantly cheaper in terms of both reallocations and CPU cycles. 现在,数据已从旧位置移动到新位置,这在重新分配和CPU周期方面可能会便宜得多。 In particular, the
wstring
s inside abc
s would not require copying the content of the string itself, which may be a rather big potential saving. 特别是,
abc
内的wstring
不需要复制字符串本身的内容,这可能会节省很多钱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.