Updating an Object's property in a Vector

限于喜欢 提交于 2019-12-11 03:06:36

问题


I have a vector which contains objects. The objects have a property called first name. I want to update the first name in a property, in order to do that i have to pass the vector which the objects are saved, staff number which uniquely identifies each object and finally the new name taken from the user input.

My problem is it displays the update name in the loop which i use to set the new name but if i use a second loop or a new loop and iterate through the vector again, the new name isn't saved but the old name is displayed.

Here is what i have done :-

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

}

What seems to be the problem here ? Thank you


回答1:


You pass a vector by value

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

so each time you call this function you will copy original vector into it and work on this copied vector inside the function. The result of this is the changes are made to local variable inside function. Instead you want to pass vector by reference:

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

In function body, here

for( Administrator iter: vectorUpdate)

you will experienced the same thing. You want to write:

for( Administrator& iter: vectorUpdate)


来源:https://stackoverflow.com/questions/23848343/updating-an-objects-property-in-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!