Попытка проверить цикл для Nullptr C ++ - PullRequest
0 голосов
/ 28 ноября 2018

Я пытаюсь выяснить, как альтернативно проверить, является ли указатель в массиве в настоящее время NULL, и выполнить цикл.В тот момент, если содержимое этой части массива будет удалено, при циклировании будет выдано сообщение об ошибке.

Этот массив инициализирован:

Student *classRosterArray[5] = { nullptr, nullptr, nullptr, nullptr, nullptr };

Цикл

void Roster::add(string studentID, string firstName, string lastName, string email, int age, int daysInCourse1, int daysInCourse2, int daysInCourse3, Degree degreeProgram)
{
    int courseDaysin[3] = { daysInCourse1, daysInCourse2, daysInCourse3 };

    for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
        if (classRosterArray[i] == nullptr) {
            if (degreeProgram == NETWORKING) {
                classRosterArray[i] = new NetworkStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
            }
            else if (degreeProgram == SECURITY) {
                classRosterArray[i] = new SecurityStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
            }
            else if (degreeProgram == SOFTWARE) {
                classRosterArray[i] = new SoftwareStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
            }
            else {
                classRosterArray[i] = new Student(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram);
            }

            break;//stop 
        }
    }
}

Когда удалено:

void Roster::remove(string studentID)
{
    bool studentRemoved = false;
    for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
        if (classRosterArray[i] != nullptr && classRosterArray[i]->fetchStudentId() == studentID) {
            classRosterArray[i] = nullptr;
            studentRemoved = true;
            break;
        }
    }

    if (studentRemoved == false) {
        cout << "ERROR: Student ID '" << studentID << "' was not found.";
    }
}

Отредактировано, чтобы добавить следующие фрагменты кода с ранее предложенными изменениями, как мне следует изменить следующее теперь, когда я использую карту вместо своегооригинальный массив.Спасибо за помощь, ребята!

void Roster::printAll()
{
    for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
        classRosterArray[i]->print();
    }
}

void Roster::printByDegreeProgram(int degreeProgram)
{
    for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
        if (classRosterArray[i]->fetchDegreeProgram() == degreeProgram) {
            classRosterArray[i]->print();
        }
    }
}

void Roster::printDaysInCourse(string studentID)
{
    float avg = 0;
    int max = 3;
    for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
        if (classRosterArray[i] != nullptr && classRosterArray[i]->fetchStudentId() == studentID) {
            int *daysInCourse = classRosterArray[i]->fetchDaysInCourse();
            for (int x = 0; x < max; x++) {
                avg += daysInCourse[x];
            }

            cout << "Student " << classRosterArray[i]->fetchStudentId() << "'s average number of days in each course is." << (avg / max) << "\n";
            break;
        }
    }
}

void Roster::printInvalidEmails()
{
    for (int i = 0; i < sizeof(classRosterArray) / sizeof(classRosterArray[i]); i++) {
        string email = classRosterArray[email]->fetchEmail();
        bool isValid = false;

        size_t found = email.find("@");
        if (found != string::npos) {
            found = email.find(".");
            if (found != string::npos) {
                found = email.find(" ");
                if (found == string::npos) {
                    isValid = true;
                }
            }
        }

        if (!isValid) {
            cout << email << " is not a valid email address \n";
        }
    }
}

1 Ответ

0 голосов
/ 28 ноября 2018

Проблемы с вашим кодом:

  • Вы используете простые массивы C, их сложнее использовать и легче разбить
  • В вашем методе удаления вы не используете "delete"удалить объект, который вы создали с помощью «нового», так что вы пропускаете каждого удаленного студента.
  • Если у вас более 5 студентов, ваш метод добавления завершится неудачно без сообщения об ошибке
  • В реальномПрограмма, когда у вас есть огромное количество учеников, повторяет их все для каждой операции «добавить» или «удалить», это большой удар по производительности.

Вот как это должно быть написано в современном C ++:

map<string, shared_ptr<Student> > classRosterArray;

void Roster::add(string studentID, string firstName, string lastName, string email, int age, int daysInCourse1, int daysInCourse2, int daysInCourse3, Degree degreeProgram)
{
  int courseDaysin[3] = { daysInCourse1, daysInCourse2, daysInCourse3 };
  switch (degreeProgram) {
     case NETWORKING:
         classRosterArray[studentID] = std::shared_ptr<Student>(new NetworkStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram));
         break;
     case SECURITY:
         classRosterArray[studentID] = shared_ptr<Student>(new SecurityStudent(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram));
         break;
         /* [...] */
     default:
         classRosterArray[studentID] = shared_ptr<Student>(new Student(age, courseDaysin, studentID, email, firstName, lastName, degreeProgram));
  }
}

void Roster::remove(string studentID)
{
    auto it = classRosterArray.find(studentID);
    if (it != classRosterArray.end())
        classRosterArray.erase(it);
    else
        cout << "ERROR: Student ID '" << studentID << "' was not found.";
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...