Reputation: 1268
If I search a vector for a value using the standard library find()
function, will the following code return the proper references? If the search finds the desired value in the vector, it should return a reference to that value. If it does not, it should push the value onto the end and return a reference to the new value.
I can't tell. Returning a.back()
should be fine, because it's a reference by definition. It's dereferencing the iterator in the case where i
is found that I'm unsure of.
int& foo(int i)
{
std::vector<int>::iterator found = find(a.begin(), a.end(), i);
if (found != a.end())
{
return *found;
} else {
a.push_back(i);
return a.back();
}
}
I can't tell. Returning a.back()
should be fine, because it's a reference by definition. It's dereferencing the iterator in the case where i
is found that I'm unsure of. The whole point, as is probably obvious, is to get the function to act as an lvalue. It certainly compiles, but I'm not sure if it's correct.
Upvotes: 0
Views: 111
Reputation: 56509
It's OK in both cases.
Per § 24.2.2 / Table 106 : For iterator r
, expression *r
returns a reference.
Per § 23.3.6.1 : method back()
returns a reference.
And you can return them as references too.
Upvotes: 1
Reputation: 153955
When dereferencing an iterator you get a reference. Basically, a.back()
is equivalent to *(a.end() - 1)
(for containers with random access iterators). That is, the function looks OK. Note, that references to std::vector<T>
elements stay valid until the vector is destroyed or elements are relocated, e.g., due to resizing the vector.
Upvotes: 2