Elegant ways to return multiple values from a function

后端 未结 14 858
梦谈多话
梦谈多话 2020-12-15 03:49

It seems like in most mainstream programming languages, returning multiple values from a function is an extremely awkward thing.

The typical soluti

相关标签:
14条回答
  • 2020-12-15 04:52

    By the way, Scala can return multiple values as follows (pasted from an interpreter session):

    scala> def return2 = (1,2)
    return2: (Int, Int)
    
    scala> val (a1,a2) = return2
    a1: Int = 1
    a2: Int = 2
    

    This is a special case of using pattern matching for assignment.

    0 讨论(0)
  • 2020-12-15 04:54

    In C++ you can pass a container into the function so the function can fill it:

    void getValues(std::vector<int>* result){
      result->push_back(2);
      result->push_back(6);
      result->push_back(73);
    }
    

    You could also have the function return a smart pointer (use shared_ptr) to a vector:

    boost::shared_ptr< std::vector<int> > getValues(){
      boost::shared_ptr< std::vector<int> > vec(new std::vector<int>(3));
      (*vec)[0] = 2;
      (*vec)[1] = 6;
      (*vec)[2] = 73;
      return vec; 
    }
    
    0 讨论(0)
提交回复
热议问题