If the function return value is a pointer, you can return nullptr.
If the function return value is a reference, you can generate a static object within the search function, and then return the reference of this object whenever it cannot be found.
class User;
class UserList;
User &find(UserList &ul) {
static const User user;
// ...
return user;
}
Usually, the above two methods are not used in this situation, because the corresponding iterator (iterator) is often designed when designing the UserList class, so that the return value of the function is the iterator. The iterator exists to point to the one-past-last element, that is, it cannot be found. For example for vector class:
In fact, iterators and pointers are a good solution, and exceptions are also a good solution. The results can be judged as easily as the return value. However, exceptions are rarely designed when writing C++ code.
If the function return value is a pointer, you can return
nullptr
.If the function return value is a reference, you can generate a
static
object within the search function, and then return the reference of this object whenever it cannot be found.Usually, the above two methods are not used in this situation, because the corresponding iterator (iterator) is often designed when designing the
UserList
class, so that the return value of the function is the iterator. The iterator exists to point to the one-past-last element, that is, it cannot be found. For example forvector
class:The corresponding search function is:
I also mention two methods
1. Throw exception
2. Multiple return values
Return values can be created using functions like make_tuple, make_pair
In fact, iterators and pointers are a good solution, and exceptions are also a good solution. The results can be judged as easily as the return value. However, exceptions are rarely designed when writing C++ code.