2-dimensional vectors

This is a discussion on 2-dimensional vectors within the C++ Programming forums, part of the General Programming Boards category; Hello, I want to insert some My_Struct* pointers into a 2-dimensional array. In a 1-dimensional array, I normally do this ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Posts
    36

    2-dimensional vectors

    Hello,

    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:

    Code:
    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();
            my_vector.push_back(x);
        }
    }
    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?

    Thanks

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    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:
    Code:
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21