【问题标题】:c++ 2d array of class pointersc++ 2d 类指针数组
【发布时间】:2017-05-14 21:13:06
【问题描述】:

我正在尝试创建一个包含我的班级指针的二维数组。首先,我想将它们全部分配为 NULL:

Timetable::Timetable(int hours) : TimetableBase(hours){
    scheduledLectures = new Lecture**[5];
    for (int i = 0; i < 5; i++) {
        scheduledLectures[i] = new Lecture*[hours];
        for (int j = 0; j < hours; j++)
            scheduledLectures[i][j] = NULL;
    };
}

这是一个时间表生成器应用程序。我有一个函数可以将这些指针设置为特定对象。

void Timetable::setLecture(Lecture& lecture){
    while ((lecture.getDuration()) -1 > 0){
        scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
    }
}

编译器不会为此返回任何错误,但在运行时,指针似乎仍为 NULL。 我确信错误在 setter 函数内部(并且几乎可以肯定它是一个语法错误),但我找不到解决方案。 这里有什么问题?

谢谢

【问题讨论】:

标签: c++ arrays class pointers


【解决方案1】:

使用vector(或std::array)指针或shared_ptrs(或unique_ptrs,具体取决于您的生命周期的排列方式),而不是您自己管理的二维指针数组。省去手动管理对象的内存和生命周期的麻烦。

class TimeTable {
    vector<vector<shared_ptr<Lecture>>> scheduledLectures;
};

Timetable::Timetable(int hours) 
        : TimetableBase(hours), 
        scheduledLectures(5, vector<shared_ptr<Lecture>>(5)) {}

void Timetable::setLecture(std::shared_ptr<Lecture> lecture){
    while ((lecture->getDuration()) -1 > 0) { // not sure what this does
        scheduledLectures[lecture->getDayScheduled()][(lecture->getHourScheduled())+1] = lecture;
    }
}

您可以测试shared_ptr 是否为空,如下所示

auto s_ptr = std::shared_ptr<int>{}; // null
// either assign it to a value or keep it null
if (s_ptr) { 
    // not null
}

如果您在其他地方管理 Lecture 对象的内存,那么只需使用 2D 指针向量并信任您的代码

class TimeTable {
    vector<vector<Lecture*>> scheduledLectures;
};

Timetable::Timetable(int hours) 
        : TimetableBase(hours), 
        scheduledLectures(5, vector<Lecture*>(5)) {}

void Timetable::setLecture(Lecture& lecture){
    while ((lecture.getDuration()) -1 > 0) { // not sure what this does
        scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
    }
}

【讨论】:

  • 请不要将向量的向量用作二维数组。制作一个扁平的二维数组类并不难。
  • @Sopel 不,使用vector 抽象出平面二维数组的管理内存并不过分。如果您这么认为,请使用std::array
  • 1.向量向量具有更多分配的不必要开销(也可能更差的局部性) 2. 代码不将其用作锯齿状数组并不明显。 3.你不需要vectlr的动态部分
  • @Sopel 开销是什么?只有当迫切需要不惜一切代价最小化分配时,这种主张才合理。向量分配是 O(1) 摊销的,因为向量在需要重新分配内存时会加倍,因此在大量插入序列中成本并没有那么高。当您谈论更少的元素时,它根本没有那么多,因为分配更少。如果您绝对不能进行分配,那么std::array 效果很好。
  • 关于2,即使不需要锯齿状数组也可以使用向量。关于3,然后使用std::array,使用new的用户表示5不是一成不变的。 OP的代码是动态分配内存的,切换到vector实现时分配的次数很可能完全一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
相关资源
最近更新 更多