我有一个包含对象的 vector 。这些对象具有称为名字的属性。我想更新属性中的名字,为此,我必须传递保存对象的 vector ,唯一标识每个对象的人员编号以及最终从用户输入中获取的新名称。

我的问题是它在循环中显示更新名称,我用它来设置新名称,但是如果我使用第二个循环或新循环并再次遍历 vector ,则不会保存新名称,但会显示旧名称。

这是我所做的:-

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.
        }
    }

}

这里似乎是什么问题?谢谢

最佳答案

您通过值传递 vector

void updateFirstName(vector<Administrator> vectorUpdate,
                                        string staffNumber,string newName)

因此,每次调用此函数时,您都会将原始 vector 复制到其中,并在函数内部处理此复制的 vector 。结果是对函数内部的局部变量进行了更改。相反,您想通过引用传递 vector :
void updateFirstName( vector<Administrator> &vectorUpdate,
                                        string staffNumber,string newName)

在功能主体中
for( Administrator iter: vectorUpdate)

您将经历同样的事情。您要写:
for( Administrator& iter: vectorUpdate)

10-05 18:18
查看更多