Thread: Arrays that can change size dynamically

  1. #1
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003

    Arrays that can change size dynamically

    Hi everyone,

    I want to start making a sort of strategy game, where every 'unit' in the game will be stored in an array. I have a UNIT class that holds info on each unit.

    What I want to do is to be able to re-size the array as each new unit is made. For example:
    // Game starts
    UNIT * UnitArray[N] = new UNIT (with whatever we need to make 10 of them)
    // A new unit is created
    UnitArray[N+1] = new UNIT;
    I hope you can understand what I mean. Really all I want is to learn how to create an array that can change its size.

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Do a google search for stl vector

    Those array classes are provided by every major C++ compiler, and they expand as needed when memory's availiable.

    If you want to do it yourself...

    1) Create a class for your array
    2) Overload the [] brackets operator to make sure the memory has been allocated. That function should also returns a reference to allow programs to assign to it, and to read that value.

  3. #3
    Banned nickname_changed's Avatar
    Join Date
    Feb 2003
    Thanks, I found some info on Vectors and I have them working perfectly. Thanks very much! (Y)

  4. #4
    Registered User
    Join Date
    May 2003
    Well, if you're going to iterate through them (i.e. you only access array[5] after array[4] and before array[6]), use linked lists.

    Problem with vectors is that addition tends to be slower. Vectors/arrays are nice when you need random access (you want to be able to access any given element in equal time), but if you are going to access the elements one at a time, you're better off with a linked list; it takes less time to add an element.

    I dunno how the vector template is implemented internally (there are ways to make it less slow), but linked lists tend to work better if you're only accessing them sequentially anyway.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  2. dynamically setting size of 2d char array
    By waxydock in forum C Programming
    Replies: 4
    Last Post: 05-13-2007, 10:58 PM
  3. Is there a limit to the size of 2-D arrays?
    By ashley in forum C Programming
    Replies: 2
    Last Post: 01-04-2007, 04:01 PM
  4. Dynamically allocated arrays
    By axe786 in forum C Programming
    Replies: 6
    Last Post: 12-03-2004, 01:41 AM
  5. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM