Thread: Inserting elements into array

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912

    Inserting elements into array

    Let's say I have a 2D array, that has 10 rows, and new rows keep coming into the program. When a new row comes in, I want all the rows to be moved up one index number, and have the oldest one removed from the array. Is there a single function, or a simple way to do this, or am I going to have to do a whole bunch of swapping?

  2. #2
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    You could also do a modified sort of linked list thing... with a permanent head node that doesn't actually store data, but is just a pointer to the first dynamically allocated node. When you get a new "row" you could create a new node for it, stick it on the end, and then change the head node to point at the second node in the list and delete the first... making the second the first. That was confusing. It would also require a lot of calls to new and delete if you're doing this a lot. Salem's way might be better - I didn't take time to really read his code carefully. It probably depends on how much you are going to be doing this.
    Away.

  3. #3
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    It probably depends on how much you are going to be doing this.
    .... About 25 times per second... I'll try Salem's way....

  4. #4
    Registered User
    Join Date
    Jun 2003
    Posts
    245
    Why not use a vector? push_front and erase come to mind and the rest is done for you.

  5. #5
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    That's not a bad idea. Having a 1d array of classes would actually solve a lot of other problems for me.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using realloc for a dynamically growing array
    By broli86 in forum C Programming
    Replies: 10
    Last Post: 06-27-2008, 05:37 AM
  2. Shifting elements in an Array
    By mmarab in forum C Programming
    Replies: 5
    Last Post: 12-10-2007, 12:11 PM
  3. Template Array Class
    By hpy_gilmore8 in forum C++ Programming
    Replies: 15
    Last Post: 04-11-2004, 11:15 PM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. A simple question about selecting elements in an array
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 08-30-2001, 10:37 PM