我有一个包含对象的向量。这些对象有一个称为名字的属性。我想更新属性中的名字,为了做到这一点,我必须传递保存对象的向量、唯一标识每个对象的员工编号,最后是从用户输入中获取的新名称。
我的问题是它在循环中显示更新名称,我用它来设置新名称,但如果我使用第二个循环或新循环并再次迭代向量,则不会保存新名称,但会显示旧名称。
这是我所做的:-
public: void updateFirstName(vector<Administrator> vectorUpdate,string staffNumber,string newName)
{
FileHandler<Administrator> adminTObj;
for(Administrator iter: vectorUpdate)
{
if(iter.getStaffNumber()==staffNumber)
{
iter.setFirstName(newName);
cout<<"Update"<<endl;
cout<<iter.getFirstName()<<endl;
//here it prints the updated name but if i use a different loop
//and iterate through the vector the new name is not saved.
}
}
}
这里似乎有什么问题?谢谢
您按值传递向量
void updateFirstName(vector<Administrator> vectorUpdate,
string staffNumber,string newName)
因此,每次调用此函数时,您都会将原始向量复制到其中,并在函数内处理此复制的向量。其结果是对函数内部的局部变量进行更改。相反,您想通过引用传递向量:
void updateFirstName( vector<Administrator> &vectorUpdate,
string staffNumber,string newName)
在函数体中,这里
for( Administrator iter: vectorUpdate)
你也会经历同样的事情。你想写:
for( Administrator& iter: vectorUpdate)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)