So right now I have the following:
boost::ptr_vector <Customer> cvect;
ifstream cDbase("datafiles/customers.txt");
while (cDbase.good())
{
while (!cDbase.eof())
{
cDbase >> newCust;
Customer* c = &newCust;
cvect.push_back(c);
}
}
for (unsigned int loop = 0; loop < cvect.size(); loop++)
{
cout << cvect[loop];
}
When I try to print the customer details, it prints out blank lines. How do I dereference ptr_vector properly?
The Boost pointer-containers are for containers which own dynamically-allocated objects. So to use it as intended, you'd do this:
while (cDbase >> newCust) {
cvect.push_back(new Customer(newCust));
}
(Note: never loop on eof()
).
However, do you really need to store them dynamically? How about simply this:
std::vector<Customer> cvect;
ifstream cDbase("datafiles/customers.txt");
while (cDbase >> newCust) {
cvect.push_back(newCust);
}
If newCust
is a local variable, you push a pointer to a local variable into the vector which will not work.
Instead you have to create a new object each time through the loop. A simple solution would look something like this:
while (cDbase >> newCust)
cvect.push_back(new Customer(newCust));
This might require you to have a proper copy-constructor in place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.