交叉向量中的分段错误

时间:2016-09-25 14:10:28

标签: c++

我正在尝试提供一个学生矢量和一个大学矢量,每个学生都有一份他正在申请的大学名单,每所大学都有一份申请的学生名单。 但是当我运行代码时,会出现“Segmentation fault:11”。请你帮我理解,我做错了。

struct Student;

struct Univercity
{
    std::string name;
    int vacancies;
    std::vector<Student *> students;

    Univercity(std::string name,
               int vacancies)
        : name(name),
          vacancies(vacancies) {}
};

struct Student {
    std::string name, surname;
    int d, m, y;
    int points;
    std::vector<Univercity *> univercities;

    Student(std::string name,
            std::string surname,
            int d, int m, int y, int points,
            std::vector<Univercity *> univercities)
        : name(name),
          surname(surname),
          d(d), m(m), y(y),
          univercities(univercities) {}
};

void input(std::vector <Student> *students,
           std::vector <Univercity> *univercities) {
    int n;
    std::cin >> n;
    for (int i = 0; i < n; i++) {
        std::string name;
        int vacancies;
        std::cin >> name >> vacancies;
        univercities->push_back(Univercity(name, vacancies));
    }
    std::cin >> n;
    for (int i = 0; i < n; i++) {
        std::string name, surname;
        int d, m, y, points;
        int k;
        std::vector<Univercity *> applications;
        std::string uni_name;
        std::cin >> name >> surname >> d >> m >> y >> points >> k;
        for (int j = 0; j < k; j++) {
            std::cin >> uni_name;
            for (auto u : *univercities) {
                if (u.name == uni_name) {
                    applications.push_back(&u);
                    break;
                }
            }
        }
        students->push_back(Student(name, surname, d, m, y,
                                    points, applications));
    }

}

int main() {
    std::vector <Univercity> univercities;
    std::vector <Student> students;
    input(&students, &univercities);
    for (auto s : students) {
        std::cout << s.surname << " " << s.univercities.size() << "\n";
        for (auto u : s.univercities) {
            std::cout << u->name << " " << u->vacancies << "\n";
        }
    }
}

示例输入:

3
MSU 1
HSE 2
MIPT 100
5
Ivan Ivanov 1 1 1900 100 2 MSU HSE
Petr Petrov 2 1 1900 90 2 MSU HSE
Alexander Sidorov 3 1 1900 110 2 MIPT HSE
Ivan Petrov 3 1 1900 100 3 HSE MSU MIPT
Petr Ivanov 4 1 1900 80 1 HSE

2 个答案:

答案 0 :(得分:4)

当您阅读输入时:

for (auto u : *univercities) {
    if (u.name == uni_name) {
        applications.push_back(&u);
        break;
    }
}

在基于范围的for循环u中,是向量中元素的副本。因此,一旦离开循环,推入向量的地址就会无效。使用

for (auto& u : *univercities) { //...

使用引用并避免复制。

答案 1 :(得分:0)

applications.push_back(&u);

您正在向applications推送指向univercities元素的指针。但是univercitiesinput函数的末尾不再存在(及其所有内容)。因此,在application向量中的指针未指向现有对象之后。

不过:“大学”,而不是“大学”。

编辑:我错了。向量由指针传递,因此它仍然存在。没注意到星号,对不起。