简体   繁体   中英

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. 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? 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.

Thank you everyone.

vector.resize(...) may be of help? 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.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. 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()

It may or may not do anything different than your insert(). Values are default constructed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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