我知道这已经被问过了,但我仍然不知道该怎么做。我必须编写一个函数,该函数返回数组中出现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)

最佳答案

可以使用 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' ;

关于c++ - 如何从C++中的函数返回多个值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31737427/

10-11 23:03
查看更多