问题
I have a vector of class objects I've created in main by reading in a data file. I'm then passing around the vector to several different files containing functions that perform different operations on the vector (sorting by different fields, subtracting inventory, etc.). I'm running into a problem when I try to use push_back
to add to the vector in another file (that's a part of the same project) after it's already been created. The pre-existing vector is passed to the function and the vector is successfully added to within the function, but when I exit the function the added record is no longer there, and, as far as I can tell, I should be accessing the updated vector after that point forward from all my different functions in different files, right? I shouldn't have to pass the updated vector back if it's the same name as the one I created in main, should I? I'm sure the language and terminology I'm using are wrong (and please feel free to correct me), but it's almost as if the vector isn't updating globally and is only updating locally within the function for the duration of its call.
This is the function definition and code within the function I'm using where I want to add to the vector (I'm skipping all the variable parameter assignments for the sake of brevity). All of the functions I'm pointing to are the setter functions within the class, and prior to this point the vector already contains 20 records, and was set up similarly to the below function.
void addBook(vector<BookData> books)
{
BookData *books1;
books1 = new BookData;
books1->setTitle(bookTitle);
books1->setAuthor(author);
books1->setPub(publisher);
books1->setIsbn(isbn);
books1->setWholesale(wholesale);
books1->setRetail(retail);
books1->setQty(qtyOnHand);
books1->setDateAdded(dateAdded);
books.push_back(*books1);
}
I didn't want to flood the post with too much code but I can post more if it'd be helpful. I just want the additions (or deletions I make in another function) to be accessible throughout the whole program.
回答1:
You should pass the vector by reference to modify the original global vector.
void addBook(vector<BookData>& books)
^^^
Otherwise you are passing a copy of the original vector to the function and modifying that not the global version.
回答2:
You need to pass your vector as a reference wherever necessary. In that specific instance, you just need to change
void addBook(vector<BookData> books)
to:
void addBook(vector<BookData>& books)
otherwise your function gets a copy of the vector, not a reference to the original one.
来源:https://stackoverflow.com/questions/8337493/updating-vector-of-class-objects-using-push-back-in-various-functions