Reputation: 10016
My goal is to create an array of vectors (with a capacity of 10 integers for each vector) on the heap. I can create my array easily enough:
vector<int>* test = new vector<int>[NUM_VERTS];
However, this creates an array of empty vectors. I know each vector will store at least 10 ints and so I want to create the vectors with size 10 to start with to avoid having them re-size themselves multiple times (I'm reading in a big file and so efficiency is important). How can I modify the statement above so that it does what I want?
As a side note, I'm using VS 2013 and struggling with its debugger. When I run the debugger and look at the contents of test
above, it shows me the memory address of the area it points to but not the contents stored at the address. Does anyone know how I can view the contents instead of the address?
Thanks
PS I'm creating the array of vectors on the heap instead of the stack because the array is extremely large (just under a million entries). When I tried to create it on the stack I got a stack overflow error.
Upvotes: 1
Views: 3635
Reputation: 114461
You can create a vector
of vector
s that is not the same as an array but for your use case it should be equivalent:
std::vector< std::vector<int> > test(NUM_VERTS, std::vector<int>(10));
there's no need to allocate it with new because vector
elements are already on the heap.
If you need the pointer to the first contained vector you can just use
std::vector<int> *p = &test[0];
and use p
as if it was an heap-allocated array of vectors (all the elements of a vector
are guaranteed to be consecutive in memory).
Upvotes: 3