Archived

This topic is now archived and is closed to further replies.

HellRiZZer

STL vector troubles... please help..

Recommended Posts

I got a declaration
  
vector<Object *> Array;
  
When I try to set it to something, it gives me error (0xC0000005)(Assign pointer to another pointer if first isn't NULL(not initialized)) So, I tried
  
for (i=0; i<MySize; i++)
    Array[i] = NULL;
  
it gives me same error as above. So, what should I do to correctly initialize a vector Array to use it? Thanks. " Do we need us? "

Ionware Productions - Games and Game Tools Development edit: added source tags Edited by - Stoffel on February 21, 2002 10:00:40 PM

Share this post


Link to post
Share on other sites
The syntax is ''vector variable'', where ''type'' is the name of the type in the vector, and ''variable'' is the name of the vector variable. As in, ''vector aVar'', where aVar is a vector of elements of type ''int''.

Look up templates in your C++ manual for more details.

Share this post


Link to post
Share on other sites
Your vector has a size 0 by default. If you want to set the value of the first element, you should either do something like this:
  
Array.resize (10); // now has 10 elements

Array[0] = NULL;

..or you should add data by using push_back
  
Array.push_back (NULL); // adds null to the end of vector


You should know that the default behavior of STL vectors when it needs to create new data is to set it to 0. Therefore setting all these pointers to NULL is redundant. The single line:
  
Array.resize(MySize);

Will make Array contain MySize # of pointers that are all set to 0.

Share this post


Link to post
Share on other sites
Here''s a valid STL vector code:

vector vi;

vi.reserve(10);

vi.push_back(123);
vi.push_back(23);
vi.push_back(321);

// Once you initialized the vector with some elements you can access and set them like a regular array.

vi[0] = 0;
vi[1] = 1;
vi[2] = 3;

vi[3] = 100; // ERROR - you have only filled the vector with three elements.

// Also you can use the function .size() to determine vector size.

Share this post


Link to post
Share on other sites
You can also resize the vector in bulk (rather than incrementally as with push_back) using the resize function. reserve is used to pre-allocate memory for n items so that reallocation occurs only upon adding (as with push_back) element n + 1. Use reserve if you can, otherwise vector results in lots of memory thrashing. If you need to do lots of growing and/or shrinking, you may want to try list instead, since adding nodes is O(1), though access is O(n).

Share this post


Link to post
Share on other sites
You can''t limit the size of a vector. It''s designed to grow to hold whatever you put in it. If you need to limit it, you should probably wrap vector in your own class--use vector to store the actual data, and your class''s code to make sure a limit isn''t passed.

Share this post


Link to post
Share on other sites