如何在C ++中为二维数组重载operator []

时间:2015-05-05 19:59:13

标签: c++ vector

我有一个 Map 类,它使用vector<Cell>来存储Cell的二维数组。我重复了operator[]以使用map[i][j]访问地图中的数据。

我的问题是它只适用于第一行数据。一旦i = 1我收到分段错误。代码如下,任何帮助将不胜感激! 谢谢

在Map类中(如果您需要更多详细信息,请告诉我们):

/* 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++; }
    }
}

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; }
}

输出

[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

第一行输出似乎是正确的,之前使用operator()重载的测试工作正常,我真的需要使用[]代替。

1 个答案:

答案 0 :(得分:1)

我不知道为什么它失败了,但我能够通过遵循保罗建议用Map * map = new Map(20);替换Map map(20);来解决这个问题。

我的Java背景现在可能很明显。 谢谢大家!