Home  >  Q&A  >  body text

设计模式 - c++自己编写的查找函数如果查找不到应该返回什么?

比如自己写了一个User类,有一个函数是查找User并返回查找到的User类,但如果这个函数查找不到应该怎么处理,java可以返回null,但是cpp不能进行这样的类型转换。

迷茫迷茫2765 days ago609

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:33:07

    1. If the function return value is a pointer, you can return nullptr.

    2. 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;
      }
      
    3. 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:

      vector<int> vi;
      vi.end();  // one-past-last iterator

      The corresponding search function is:

      vector<int>::iterator find(vector<int> &vi);
      
      auto it = find(vi);
      if (it != vi.end()) {
        /* ... */
      } 

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:33:07

    I also mention two methods

    1. Throw exception

    User& find( ... ) 
    {
        ...
        if (not found) {
            UserNotFoundException().throw();    //在函数调用外部try.catch,跟java类似
        }
    }

    2. Multiple return values

    Return values ​​can be created using functions like make_tuple, make_pair

    std::pair<User, bool> find( ... ) 
    {
        ...
        if (found) {
            return make_pair(..., true);    //在外部检查返回值 !不过只能返回拷贝!
        }
    }

    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.

    reply
    0
  • Cancelreply