在Vector中更新对象的属性

时间:2014-05-24 18:27:09

标签: c++ object c++11 vector updates

我有一个包含对象的向量。对象具有名为first name的属性。我想更新属性中的第一个名称,为了做到这一点,我必须传递保存对象的向量,唯一标识每个对象的人员编号,最后是从用户输入中获取的新名称。

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

以下是我所做的: -

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

}

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

1 个答案:

答案 0 :(得分:2)

按值传递矢量

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)
相关问题