c++ - 类中的函数在从向量调用时不起作用包含所有类对象
问题描述
我创建了一个名为的类,其中包含一个名为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 中创建了一个类似的代码,它可以工作。但是,它很慢。
解决方案
问题是将副本vector::push_back()
推送到. 因此,和是内存中独立的对象,每个都有自己的. 因此,对 所做的任何更改都不会反映在 中,反之亦然。school
vector
school
all_institutions[0]
institution
vector
school
all_institutions[0]
要在内存中创建school
和all_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");
推荐阅读
- excel - 使用scala从excel构造一个数据框
- html - 转换节点上的 CSS 边框
- sql - 不像 '%gmaii.co%' 不工作
- javascript - var let 可以,但 let let 不行吗?
- android - 将 GDPR 添加到 Android Studio
- wpf - WPF 使用 DataTrigger 为 RenderTransform 设置动画
- php - 浏览器关闭时cookie php被删除
- sql-server - SSMS 创建引用一个表的多个外键
- javascript - Node.js 会继续支持它的旧版本节点模块吗
- c# - 如何在 http 响应中表示“字段结束”?