我正在尝试编写一个函数,将信息从文本文件输入到 map 中。我的主要代码如下:
int main(){
typedef map<int,student*> record;
record allstudents;
fileinput("inputtest.txt",allstudents);
//rest of code....
}
其中函数“fileinput”定义为:
void fileinput(string datafile, record map){
fstream file1(datafile);
if(!file1.good()){
//error code
}
//Pulls information from file
student* S1= new physics(name,ID); //creates a new pointer
//(*S1).printinfo(); //Can print info if required for de-bug
map[ID]=S1; //store to map
entries++; //counts entries read in
}
cout<<"Import complete. "<<entries<<" new students entered."<<endl;
}
当我从测试文件运行这段代码时,如果我取消注释 (*S1).printinfo();
它将读入数据并正常输出,并且会正确计算数量已经读入的学生数量。但是,当我回到我的主要功能并输出现在存储在 allstudents
中的内容时,那里似乎什么都没有?
为什么会发生这种情况,有人知道解决这个问题的方法吗?我已经删减了很多代码以尝试使其更易于阅读,但如果您需要查看其余部分,我可以随时对其进行编辑。
谢谢。
最佳答案
这是因为您要传入 map
按值。将函数的签名更改为
void fileinput(string datafile, record &map)
简短说明:当您按值传递时,会生成参数 (map
) 的拷贝。在您的函数中,您对该拷贝执行修改,但当函数返回且拷贝超出范围时,这些修改将丢失。它们不会自动传播回“源”对象。
关于c++ - 存储到函数内的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10259262/