I want to return a reference of an object from a vector, and the object is in an iterator object. How can I do that?
I tried the following:
Customer& CustomerDB::getCustomerById (const string& id) {
vector<Customer>::iterator i;
for (i = customerList.begin(); i != customerList.end() && !(i->getId() == id); ++i);
if (i != customerList.end())
return *i; // is this correct?
else
return 0; // getting error here, cant return 0 as reference they say
}
In the code, customerList is a vector of customers, and the function getId returns the id of the customer.
Is the *i correct? And how can I return 0 or null as a reference?
return *i;is correct, however you can’t return 0, or any other such value. Consider throwing an exception if the Customer is not found in the vector.Also be careful when returning references to elements in vector. Inserting new elements in vector can invalidate your reference if vector needs to re-allocate its memory and move the contents.