Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return reference of an object from an iterator

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?

like image 518
hakuna matata Avatar asked May 11 '12 10:05

hakuna matata


People also ask

How do I return an iterator in C++?

In C++, the iterator is designed to behave like a super-pointer. Thus, it usually "points" to the value, and using the operator ++, --, etc. (depending on the exact type of the iterator), you can move the iterator to "point" to the next, previous, etc. value in the container.

Can you return an iterator?

Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.

Can you pass an iterator by reference?

You could pass a const reference, but usually iterators are small enough that it gives no advantage over passing by value.

How do I access vector iterator?

You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively. using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector. push_back("a"); myvector.


2 Answers

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.

like image 113
reko_t Avatar answered Oct 13 '22 12:10

reko_t


There is no such thing as a "null" reference: if your method gets an id that's not in the vector, it will be unable to return any meaningful value. And as @reko_t points out, even a valid reference may become invalid when the vector reallocates its internals.

You should only use reference return types when you can always return a reference to an existing object that will stay valid for some time. In your case, neither is guaranteed.

like image 33
suszterpatt Avatar answered Oct 13 '22 11:10

suszterpatt