Aerozeek
Aerozeek

Reputation: 505

How to Overload operator[] for a Two-Dimmensional Array in C++

I have a class Map that uses a vector<Cell> to store a two dimensional array of Cells. I overloaded operator[] to access the data inside Map using map[i][j].

My problem is that it only works for the first row of data. As soon as i = 1 I get a Segmentation Fault. The code is below, any help will be greatly appreciated! Thank you.

Inside the Map class (If you need more details let me know):

/* Declaration of the vector<Cell> */
vector<Cell> map_;

/* The Operator Overload */
const Cell* operator[](int x) const {
    return &map_[x * this->width_];
}

/* Constructor */
explicit Map(double mapStep) : stepSize_(trunc(mapStep * 1000) / 1000) {
    if (mapStep > 0) {
        this->height_ = trunc((ARENA_HEIGHT / mapStep));
        this->width_ = trunc((ARENA_WIDTH / mapStep));
    } else { cerr << "Map Constructor Error #2" << endl; return; }

    mapInit();
}

void mapInit() {
    int i = 0, j = 0;
    this->map_.resize(this->height_ * this->width_);

    for (auto &cell : this->map_) {
        cell = Cell(Cell::cell_type::NOGO, i, j);
        if (j < this->width_ - 1) { j++; } else { j = 0; i++; }
    }
}

The code in main():

int i = 0, j = 0;
Map * map = new Map(20);

for (; i < map->getHeight() ;) {
    cout << "[" << map[i][j]->x << ", " << map[i][j]->y << ", " << map[i][j]->t << "]";

    if (j < map->getWidth() - 1) { j++; } else { j = 0; i++; cout << endl; }
}

The Output

[0, 0, 255][1, 0, 255][2, 0, 255][3, 0, 255][4, 0, 255][5, 0, 255][6, 0, 255][7, 0, 255][8, 0, 255][9, 0, 255][10, 0, 255][11, 0, 255]
Segmentation fault

The first line of output seems to be correct, and previous tests using an overload of operator() worked fine, I just really need to use [ ] instead.

Upvotes: 0

Views: 88

Answers (1)

Aerozeek
Aerozeek

Reputation: 505

I don't know why it was failing, but I was able to fix it by following Paul's suggestion to replace Map * map = new Map(20); with Map map(20);

My Java background is probably obvious now. Thank you all!

Upvotes: 1

Related Questions