简体   繁体   English

如何在C ++中更改STL容器的大小

[英]How to change size of STL container in C++

I have a piece of performance critical code written with pointers and dynamic memory. 我有一段用指针和动态内存编写的性能关键代码。 I would like to rewrite it with STL containers, but I'm a bit concerned with performance. 我想用STL容器重写它,但是我有点担心性能。 Is there a way to increase the size of a container without initializing the data? 有没有办法在不初始化数据的情况下增加容器的大小?

For example, instead of doing 例如,而不是做

ptr = new BYTE[x];

I want to do something like 我想做类似的事情

vec.insert(vec.begin(), x, 0);

However this initializes every byte to 0. Isn't there a way to just make the vector grow? 但是,这会将每个字节初始化为0。难道没有办法使向量增长吗? I know about reserve() but it just allocates memory, it doesn't change the size of the vector, and doesn't allows me to access it until I have inserted valid data. 我知道reserve(),但它只是分配内存,它不会改变向量的大小,并且在插入有效数据之前不允许我访问它。

Thank you everyone. 谢谢大家。

vector.resize(...) may be of help? vector.resize(...)可能有帮助? You can specify the size that you want to resize to (going larger or smaller) and also intialize what you want the new elements to be initialized to. 您可以指定要调整大小的大小(变大或变小),还可以初始化想要将新元素初始化为的大小。

vec.resize( newsize ) is defined to have the same effect as vec.resize( newsize )被定义为具有与

vec.insert( vec.end(), newsize - vec.size(), T() )

if newsize > vec.size() … but the compiler may have difficulty determining that it is growing, not shrinking, and by how much. 如果newsize > vec.size() …但是编译器可能难以确定它正在增长,没有缩小以及增长多少。 You might try profiling with both. 您可以尝试对两者进行概要分析。

If you're sure that the default initialization is taking time, explicitly eliminate it with your own constructor. 如果您确定默认初始化需要花费时间,请使用自己的构造函数显式消除它。 (Even if the implicit constructor is fine, it's good to show intent.) (即使隐式构造函数很好,显示意图也很好。)

struct BYTE {
    char v;
    BYTE() {} // no default initialization!
    BYTE( char x ) : v(x) {}
    operator char&() { return v; }
    operator char const&() const { return v; }
    char *operator&() { return &v; } // not sure about operator&...
    char const *operator&() const { return &v; } // probably good in this case
};

resize() resize()

It may or may not do anything different than your insert(). 它可能会执行也可能不会执行与insert()不同的任何操作。 Values are default constructed. 值是默认构造的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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