I've made some minimal code
vector<int> items = {1, 2, 5, 0, 7};
int& getAtSafe(unsigned n) {
if (n < items.size() && items[n] != 5) return items[n];
else // ???
}
But how to return something as null when we can't find needed item?
P.S. Original task is searching item with property equal to.
Exception variants not accepted. I do not need to pause the program.
As an example, user types index, and each time when it's wrong, the user gets "Bad input"
C++ has value semantics. There are nullptr
s but there is no null value. A reference always references something. Ergo, there cannot be a reference to null.
Several options you have:
std::vector::at
does exactly that (but I suppose your code is just an example for a more general situation)nullptr
(not recommended, because then you put the resonsibility on handling it correctly on the caller)std::optional
. Again this forces the caller to handle the case of "no value returned" but in contrast to returning a nullptr
the caller gets a well-designed interface that is hard to use wrong.end
is often used to signal "element not found" throughout the standard library, so there will be little surprise if you do the same.std::vector::at
instead of your handwritten function and be done with it.P.S. Original task is searching item with property equal to.
You should use std::find
to find an item in a container. It returns end
of the container when the element cannot be found.