如何从c ++中的函数返回多个值?

时间:2015-07-31 03:04:48

标签: c++

我知道之前有人问过,但我还是不知道怎么做。我必须写一个函数,它返回数组中出现的2,5和9的次数。

    include <iostream>

    int twofivenine(int array[], int n)
    {
        int i = 0;
        int num_2 = 0;
        int num_5 = 0;
        int num_9 = 0;

        for ( i = 0;  i < n; i++ ){
            switch(){
                case (array[i] == 2):
                    num_2++;
                case (array[i] == 5):
                    num_5++;
                case (array[i] == 9):
                    num_9++;
            }

        }

       return ;
    }


    int main()
    {
        int array[6] = {2,2,3,5,9,9};

        std::cout << "2: 5: 9:" << twofivenine(array, 6) << std::endl;
    }

我只是不确定如何返回(num_2,num_5和num_9)

4 个答案:

答案 0 :(得分:10)

可以使用std::tuple

std::tuple<int, int, int > twofivenine( int array[], int n)
{
  // 
  return make_tuple( num_2, num_5, num_9 );
}

  auto x = twofivenine( array, 6 );
  std::cout << std::get<0>( x ) << '\n'
            << std::get<1>( x ) << '\n'
            << std::get<2>( x ) << '\n' ;

答案 1 :(得分:4)

有很多方法可以解决这个问题。

  1. 通过引用传递值。您可以调用以下函数:
  2. 示例:

    void foo(int &a, int &b, int &c)
    {
        // modify a, b, and c here
        a = 3
        b = 38
        c = 18
    }
    
    int first = 12;
    int second = 3;
    int third = 27;
    foo(first, second, third);
    // after calling the function above, first = 3, second = 38, third = 18
    
    1. 存储要在数据类型中返回的值。使用标准库中的数据类型,例如std::vectorstd::setstd::tuple等。保存您的值然后返回整个数据成员。
    2. 示例:

      std::vector<int> foo()
      {
          std::vector<int> myData;
          myData.pushBack(3);
          myData.pushBack(14);
          myData.pushBack(6);
          return myData;
      }
      // this function returns a vector that contains 3, 14, and 6
      
      1. 创建一个对象以保存您的值。创建一个对象,例如structclass来保存您的值并返回您的函数中的对象。
      2. 示例:

        struct myStruct
        {
            int a;
            int b;
            int c;
        };
        
        myStruct foo()
        {
            // code here that modifies elements of myStruct
            myStruct.a = 13;
            myStruct.b = 2;
            myStruct.c = 29;
            return myStruct;
        }
        // this function returns a struct with data members a = 13, b = 2, and c = 29
        

        您选择的方法最终取决于具体情况。

答案 2 :(得分:2)

通过引用传递对象,即

void twofivenine(int array[], int n, int &num_2, int &num_5, int &num_9)
{
    //Don't redeclare num_2...
}

这样打电话:

int num_2, num_5, num_9;
twofivenine(array, 6, num_2, num_5, num_9);

答案 3 :(得分:1)

按值返回一个struct,其中count为数据成员:

struct Result {
   int num_3;
   int num_5;
   int num_9;
};

Result twofivenine(int array[], int n)
{
.
.
.
    return Result{num_2, num_5, num_9};
}

并在主要:

Result result(twofivenine(array, 6));
std::cout << "2: " << result.num_2 << "5: " << result.num_5 << "9: " << result.num_9 << std::endl;

大多数编译器都会执行RVO(返回值优化),其中twofivenine函数将直接写入结果结构,从而避免使用结构副本。

相关问题