简体   繁体   English

重新分配结构的std :: vector

[英]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: 更精确地:

  1. will all the data be potentially rewritten (ie all the wstrings are all rewritten, etc.) 是否所有数据都可能被重写 (即所有wstrings都被重写,等等)

or 要么

  1. a vector of struct kind-of internally "keeps record of pointers" to each individual struct, so if the vector is rewritten, only these pointers are rewritten, but not the actual data 一个结构类型的向量-内部“保留指向每个单独结构的指针的记录”,因此,如果重写该向量,则重写这些指针,而不是实际数据

?


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM