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

标签 c++ vector

我有一个使用 vector<Cell>Map 类存储 Cell 的二维数组秒。我重载了 operator[]使用 map[i][j] 访问 Map 中的数据.

我的问题是它只适用于第一行数据。一旦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() 的重载工作正常,我真的需要改用 [ ]。

最佳答案

我不知道为什么它失败了,但我能够按照 Paul 的建议替换 Map * map = new Map(20); 来修复它使用 Map map(20);

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

关于c++ - 如何在 C++ 中为二维数组重载 operator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30062153/

相关文章:

c++ - STL vector 、push_back() 和容量

r - 子集数据框行作为列表返回?

c++ - 如何从 Windows 调试在 Linux 上运行的远程程序

c++ - 在 Visual C++ 中使用 union

c++ - 将对象 int 数据成员转换为 float 并除法将奇怪的数据 cout 附加到控制台

C++ 队列 - 简单示例

.net - .NET 框架中的 Vector3 类

c++ - std::iterator_traits libstdc++ 和 libc++ 之间的分歧

c++ - 将大整数作为 vector 中的值传递时出现段错误

vector - 在 Rust 中连接向量的最佳方法是什么?