Thread: 2-dimensional vectors

  1. #1
    Registered User
    Join Date
    Aug 2006

    2-dimensional vectors


    I want to insert some My_Struct* pointers into a 2-dimensional array. In a 1-dimensional array, I normally do this by simply using the push_back function of a vector. But in 2-dimensions, this doesn't seem to work. Here is what I tried:

    vector<vector<My_Struct*> > my_vector;
    for (int i = 0; i < 5; i ++)
        for (int j = 0; j < 20; j ++)
            My_Struct* x = new My_Struct();
    I want to create a 5 x 20 vector, with each element pointing to a My_Struct object. But when I try this approach, I get the error "vector subscript out of range" at the first push_back(x) call.

    How can I do this?


  2. #2
    Registered User
    Join Date
    Jan 2005
    You have to push_back each inner vector if you want to use push_back. Do that before the inner loop starts.

    Another solution is simply to construct the vectors right away since you know the size beforehand:
    vector<vector<My_Struct*> > my_vector(5, vector<My_Struct*>(20));
    Then instead of push_back you can access each location with [i][j] notation. They default to null pointers until you initialize them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Multi dimensional array
    By $l4xklynx in forum C Programming
    Replies: 7
    Last Post: 01-03-2009, 02:56 AM
  2. Vectors
    By naseerhaider in forum C++ Programming
    Replies: 11
    Last Post: 05-09-2008, 08:21 AM
  3. How can i made vectors measuring program in DevC++
    By flame82 in forum C Programming
    Replies: 1
    Last Post: 05-07-2008, 02:05 PM
  4. How properly get data out of vectors of templates?
    By 6tr6tr in forum C++ Programming
    Replies: 4
    Last Post: 04-15-2008, 10:35 AM
  5. multi dimensional vectors
    By r0bbb in forum C++ Programming
    Replies: 4
    Last Post: 03-18-2005, 07:14 AM