C++ c++;类指针的2d数组

C++ c++;类指针的2d数组,c++,arrays,class,pointers,C++,Arrays,Class,Pointers,我正在尝试创建一个包含类指针的2d数组。首先,我想将它们全部赋值为空: 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 &

我正在尝试创建一个包含类指针的2d数组。首先,我想将它们全部赋值为空:

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;
    };
}
编译器对此不返回任何错误,但在其运行时,指针似乎保持为空。 我确信错误在setter函数中(几乎可以肯定这是一个语法错误),但我找不到解决方法。 这里怎么了

感谢您

使用
向量
(或
std::数组
)指针或
共享
s(或
唯一
s,取决于您的生命周期安排),而不是您自己管理的2D指针数组。省去了手动管理对象的内存和生命周期的麻烦

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

如果您在别处管理
讲座
对象的内存,那么只需使用指针的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;
    }
}
课程表{
向量调度结构;
};
时刻表:时刻表(整数小时)
:时基表(小时),
调度结构(5,向量(5)){}
无效时间表::设置讲座(讲座和讲座){
而((touch.getDuration())-1>0){//不确定这是做什么的
ScheduledActures[touch.getDayScheduled()][(touch.getHourScheduled())+1]=&touch;
}
}

不要做一个好朋友。你可能想做一个好朋友。问题不在发布的代码中。请不要将向量向量用作二维数组。制作平面2d数组类并不难。@Sopel不,使用
向量
抽象出平面2d数组的管理内存并不过分。如果您这样认为,那么使用
std::array
1。向量向量具有更多分配的不必要开销(也可能是更差的局部性)2。代码没有将其用作锯齿数组并不明显。3.你不需要这个系统的动态部分vectlr@Sopel什么方面的管理费用?只有在迫切需要不惜一切代价最大限度地减少拨款的情况下,这种要求才是合理的。向量分配是O(1)摊销的,因为向量在需要重新分配内存时会加倍,所以在一个大的插入序列中成本不会太高。当你谈论更少的元素时,它根本就没有那么多,因为分配更少。如果您绝对不能分配,那么
std::array
工作得很好。关于2,即使您不需要交错数组,也可以使用向量。关于3,然后使用
std::array
,使用
new
的用户表示
5
不是一成不变的。OP的代码是动态分配内存的,切换到向量实现时分配的数量可能完全相同
auto s_ptr = std::shared_ptr<int>{}; // null
// either assign it to a value or keep it null
if (s_ptr) { 
    // not null
}
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;
    }
}