Thread: Erratic behaviour of vectors

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    6

    Erratic behaviour of vectors

    Hi

    The following program was my attempt to implement 2D vectors:

    Code:
    #include<cstdio>
    #include<vector>
    
    int main()
    {
    
        int size,counter=0;
        printf("Enter size:\n");
        scanf("%d",&size);
    
        std::vector< std::vector<int> > testtwo(size);
        for(int i=0;i<size;i++)
        {
            //for(int j=0;j<size;j++)
            testtwo[i].push_back(0);
        }
    
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            {
                testtwo[i][j]=(counter++);
            }
        }
    
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            {
                printf("%4d",testtwo[i][j]);
            }
            printf("\n\n");
        }
    }
    The for loop has been commented on purpose. If it is uncommented, the output would be as expected...
    0 1 2

    3 4 5

    6 7 8

    But if the for loop is commented, the output is changed to:

    0 1 4 5

    4 5 8 9

    8 9 12 13

    12 13 14 15

    Please notice that testtwo[row][col] = testtwo[row-1][col +2]. This pattern is followed throughout the output,,,

    Could someone please explain this error?

    Thanx in advance...

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    If you comment it out, you have undefined behavior because your inner vectors will all have a size of 1 (you only call push_back once per outer vector). Later you use j from 0 to size-1 to access the inner vectors, so it is out of bounds. Switch operator[] to at() and you'll get an exception.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Vectors
    By naseerhaider in forum C++ Programming
    Replies: 11
    Last Post: 05-09-2008, 08:21 AM
  2. 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
  3. 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
  4. How to use Vector's in C++ !?!
    By IndioDoido in forum C++ Programming
    Replies: 3
    Last Post: 10-14-2007, 11:13 AM
  5. Points, vectors, matrices
    By subnet_rx in forum Game Programming
    Replies: 17
    Last Post: 01-11-2002, 02:29 PM

Tags for this Thread