首页 > 解决方案 > 类中的函数在从向量调用时不起作用包含所有类对象

问题描述

我创建了一个名为的类,其中包含一个名为institution的函数,该函数add_student()接受 astring并将其添加到vector<string> accepted_students类中的 a 中。

当我通过institution对象直接调用该函数时,它可以工作。但是,当我创建一个包含多个institution对象的向量,然后for按索引从循环中调用该函数时,该函数不起作用。

#include <iostream>
#include <vector>
using namespace std;

class institution
{
public:
    string name;
    vector<string> accepted_students;

    institution(string NAME)
    {
        name = NAME;
    }

    void add_student(string student_name)
    {
        accepted_students.push_back(student_name);
    }
};

vector<institution> all_institutions;

int main()
{
    institution school("school_name");
    all_institutions.push_back(school);

    // The following line does not add somebody_name to school.accepted_students!
    all_institutions[0].add_student("somebody_name");

    school.add_student("my_name");
    
    //The following write "my_name" only. "somebody_name" was not added to the accepted_students vector.
    for (int i = 0; i < school.accepted_students.size(); i++)
    {
        cout << school.accepted_students[i] << endl;
    }

    return 0;
}

我是 C++ 新手。我在 Python 中创建了一个类似的代码,它可以工作。但是,它很慢。

标签: c++oop

解决方案


问题是将副本vector::push_back()推送到. 因此,和是内存中独立的对象,每个都有自己的. 因此,对 所做的任何更改都不会反映在 中,反之亦然。schoolvectorschoolall_institutions[0]institutionvectorschoolall_institutions[0]

要在内存中创建schoolall_institutions[0]引用同一个对象,请使其school成为一个引用/指针all_institutions[0]

在 C++11 之前,您可以使用它:

all_institutions.push_back(institution("school_name"));
institution &school = all_institutions.back();
//institution *school = &all_institutions.back();

在 C++11 及更高版本中,您可以直接在 中使用emplace_back()来构造新institution对象,vector而无需推送副本:

all_institutions.emplace_back("school_name");
institution &school = all_institutions.back();
//institution *school = &all_institutions.back();

在 C++17 及更高版本中,emplace_back()返回对新对象的引用:

institution &school = all_institutions.emplace_back("school_name");
//institution *school = &all_institutions.emplace_back("school_name");

推荐阅读