Double trouble with vectors

Jul 20, 2013 at 9:45pm
Hi all. I'm having trouble creating a program that creates a fish tank with which fish can be added to. The function below is kind of a fish tank builder. I haven't gotten too involved in vectors until starting this program. I'm attempting to use a 2D vector to put the pieces of the fish tank in, so that they can be edited when adding a fish. But it keeps crashing.

The text based fish tank should look like this:
1
2
3
4
5
6
7
8
9
10
 _______________
|               |
|               |
|               |
|               |
|               |
|               |
|               |
|               |
|_______________|


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//This function will be called in order to fill a two dimensional array that
//represents a fish tank and then print it.  
void displayTank()
    {
        //Adjusting the size.
        tank_frame.resize(10);
        for ( int i = 0; i < 11; i++ )
        {
            tank_frame[i].resize(tank_size);
        }
        //Append first line
        for (int j = 0; j < 11; j++)
        {
            tank_frame[0][0] = ' ';
            if ( j == 0 )
            {
                for ( int i = 0; i < tank_size; i++ )
                {
                    tank_frame[j][i] = '_';
                }
            }
            //Append middle lines
            if ( j > 0 && j < 11 )
            {
                tank_frame[j][0] = '|';
                for ( int i = 0; i < tank_size; i++ )
                {
                    tank_frame[j][i] = ' ';
                }
                tank_frame[j][6] = '|';
            }

        }

        //Print tank
        for ( int j = 0; j < tank_frame.size(); j++ )
        {
            for ( int i = 0; i < tank_frame[j].size(); i++ )
            {
                char print = tank_frame[j][i];
                cout << print;
            }
        }
    }
Jul 20, 2013 at 9:48pm
You resize tank_frame to size 10 but your loops assume it has 11 elements.
Jul 20, 2013 at 9:53pm
But my loops are to continue until less than 11. Isn't that ten? Maybe I'm looking at the wrong thing.
Jul 20, 2013 at 10:03pm
Yes, but tank_frame[10] is the 11th element. Remember that indices starts at 0.
Jul 20, 2013 at 10:07pm
Oh! I see. Thank you very much. I'm having another problem when writing to elements of the vector using a variable and a constant. If I write line 14 like this:
 
tank_frame[j][0] = ' ';

It will not print the way it does when it's written like the OP even though at that time j is equal to 0.

Lines 25 & 30 have similar problems.

[edit] Never mind. Found the problem. Thanks!
Last edited on Jul 20, 2013 at 10:44pm
Topic archived. No new replies allowed.