raven
raven

Reputation: 2564

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.

Upvotes: 1

Views: 470

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137810

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
};

Upvotes: 3

Robb
Robb

Reputation: 2686

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.

Upvotes: 4

Edward Strange
Edward Strange

Reputation: 40859

resize()

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

Upvotes: 2

Related Questions