How to instantiate a 'new' STL vector?

Started by
2 comments, last by taby 7 years, 4 months ago
Hi guys,
How do you instantiate a 'new' for STL vectors?
I have a vector of int's but if I try to exceed 1330 instances the application throws memory exceptions. So I want to pre-allocate the space with 'new'.

int frames = 1330; // 1330 max without 'new'
std::vector<int>* anim = new std::vector<int> anim(frames);
This doesn't compile, but hopefully gives an indication of what I want to do.
Any help would be greatly appreciated.
Thanks in advance :)
Advertisement

You want array of vectors....

int frames = 1330;
std::vector<int>* ivecs = new std::vector<int>[frames];

or just use a vector of vectors

typedef std::vector<int> intVector;

std::vector<intVector> anims(frames);

I have a vector of int's but if I try to exceed 1330 instances the application throws memory exceptions.


That seems concerning. 1330 ints is not very much memory - assuming an x86 processor, that's only about 5k. What exceptions? How many of these vectors do you have?

So I want to pre-allocate the space with 'new'.


std::vector has a function called "reserve" that will reserve space for a certain number of elements ahead of time. I think that's probably what you're looking for.

std::vector<int> anim;
anim.reserve(1330);

You should never really need new/delete. As mentioned above, you can use a vector< vector<int> > if you want a 2D array. Any statement where new and vector are combined is an oxymoron.

This topic is closed to new replies.

Advertisement