简体   繁体   中英

C++ vector: unused capacity

I am a new comer for C++, I am currently working on this class schedule project and the following is my add_course function. I am storing student's id, semester, and list of classes in a map. It works(I can add course to student and see it when I print a student's schedule) but every time I run the code, an exception always pop up :

Exception thrown: read access violation.
std::_Vector_alloc<std::_Vec_base_types<course *,std::allocator<course *> > >::_Myend(...) returned 0xC.

I am confusing, why is this happening. Does it mean my vector is having more capacity than it needs ?

void add_course(map<int, map<int, vector<course *> * > > &DB, int semester, int id, course c) {
    const string a = c.name;
    course* b = new course(a, c.section, c.credits);
    if (DB[id].empty()) {
        vector<course*> *p2 = new vector<course*>;
        (*p2) = { b };
        DB[id][semester] = p2; 
        return;
    }
    else
        DB[id][semester]->push_back(b);
    return;
}

Your code assumes that if DB[id] has any semesters, it has the semester semester :

if (DB[id].empty()) {
   // ...
}
else
    DB[id][semester]->push_back(b);

If that's not true, if it has some semester but not this one, then you're not catching that, and you're push_back ing on a default-constructed null pointer. This means your program has undefined behaviour, and today is the reason for the crash.

Instead you could try:

if (!DB[id].count(semester)) {
   // ...
}
else
    DB[id][semester]->push_back(b);

… which actually checks for the existence of the specific inner map element.

You would be much better off without all this dynamic allocation, though:

void add_course(
   map<int, map<int, vector<course>>>& DB,
   const int semester,
   const int id,
   const course c
)
{
    DB[id][semester].emplace_back(c.name, c.section, c.credits);
}

Isn't that nicer?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM