Updating an Object's property in a Vector

2019-07-19 15:38发布

问题:

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)