Accessing multidimensional vector in a class.

I have a class CharMap and in its constructor I have this: vector< vector<char> > CharGrid(xres, vector<char>(yres)). I don't get any errors from initializing this vector, but whenever I try to access it like this: CharGrid[gety-1][getx-1] my application crashes. How do I access the elements of this multidimensional vector?

Full code:
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Messing Around
#include <iostream>
#include <stdlib.h>
#include <vector>

using namespace std;

class CharMap
{
private:
    int xres;
    int yres;
    vector< vector<char> > CharGrid;
public:
    CharMap(int, int);
    char GetChar (int getx, int gety)
    {
        return CharGrid[gety-1][getx-1];
    };
    void WriteChar(int writex, int writey, char writechar)
    {
        CharGrid[writey-1][writex-1] = writechar;
    }
    void ClearMap()
    {
        for (int clry=0; clry<=(yres-1); clry++)
        {
            for (int clrx=0; clrx<=(xres-1); clrx++)
            {
                CharGrid[clry-1][clrx-1] = 'X';
            };
        };
    };
    void PrintMap()
    {
        system("CLS");
        for (int printy=0; printy <= (yres-1); printy++)
        {
            for (int printx=0; printx <= (xres-1); printx++)
            {
                cout << CharGrid[printy][printx];
            };
            cout << "\n";
        };
    };
};

CharMap::CharMap (int x, int y)
{
    xres = x;
    yres = y;
    vector< vector<char> > CharGrid(xres, vector<char>(yres));
};

int main ()
{
    CharMap Screen(20, 10);
    cout << 1;
    cin.get();
    Screen.PrintMap();
    cout << 2;
    Screen.WriteChar(3, 2, 'X');
    Screen.PrintMap();
    cout << 2;
    cin.get();
    return 0;
};
closed account (j3Rz8vqX)
Your CharGrid is not populated.
You are accessing bounds that are not available.

Line 52 vector< vector<char> > CharGrid(xres, vector<char>(yres)); creates a completely different vector array that is only local to the constructor; not the object.

An alternative would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CharMap::CharMap (int x, int y)
{
    xres = x;
    yres = y;
    vector<char> temp(x,'*');
    for(int i=0;i<y;++i)
    {
        CharGrid.push_back(temp);
    }
}
//...
int main ()
{
    CharMap Screen(20, 10);
    Screen.PrintMap();
    return 0;
}
********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

Process returned 0 (0x0)   execution time : 0.047 s
Press any key to continue.
Last edited on
Topic archived. No new replies allowed.