c++ - When creating a vector of objects, how to pass arguments to Default or Copy Constructor to initialize values? -
for program i'm writing project in c++ class, 1 of requirements use constructors initialize data members in objects.
we have read binary files.
the method chose accomplish was:
// loads invmast.dat or creates 1 if none exists fstream invfile; invfile.open("invmast.dat", std::fstream::in); if (!invfile) { cout << "file invmast.dat not found, creating new one." << endl; invfile.open("invmast.dat", std::fstream::out | std::fstream::app | std::fstream::binary); if (!invfile) { cerr << "unable create or open file invmast.dat; exiting." << endl; exit (exit_failure); } } cout << "file invmast.dat opened successfully." << endl; vector <inventoryitem> invmast; //vector <inventoryitem>::iterator invmastiterator; inventoryitem invloader; while ( invfile && !invfile.eof()) { invfile.read(reinterpret_cast<char *>(&invloader), sizeof(invloader)); invmast.insert(invmast.begin(), invloader); }
i'd prefer create vector of objects , pass arguments copy or default constructor, can't seem find way this.
is there way, or need rethink approach?
thanks!
if constructing element, use emplace_back
construct directly in vector
:
invmast.emplace_back(some, constructor, parameters);
but here, since you’re initialising inventoryitem
raw bytes, want construct object , move vector:
invfile.read(reinterpret_cast<char *>(&invmast.back()), sizeof(invloader)); invmast.push_back(std::move(invloader));
or default-construct element , fill it:
invmast.emplace_back(); invfile.read(reinterpret_cast<char *>(&invmast.back()), sizeof(inventoryitem));
Comments
Post a Comment