Updating vector of class objects using push_back in various functions

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;

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.


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.

Need Your Help

QFileDialog does not give selected file

c++ qt

I have a little problem using the QFileDialog in Qt 5.2. When I open the dialog the dialog will show up but does not send me any selected files back. In the code example below the 'selectedFiles.at...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.