Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values from a function in c++?

Tags:

c++

I know this has been asked before but I still don't know how to do it. I Have to write a function which returns the number of times 2, 5 and 9 appear in an array.

    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;
    }

I'm just not sure how to return (num_2, num_5, and num_9)

like image 958
Jai Avatar asked Jul 31 '15 03:07

Jai


2 Answers

Can use 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' ;
like image 198
P0W Avatar answered Oct 21 '22 08:10

P0W


There are a number of ways to approach this problem.

  1. Pass the values by reference. You can call a function such as the following:

Example:

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. Store the values to return in a data type. Use a data type from the standard library such as std::vector, std::set, std::tuple, etc. to hold your values then return that entire data member.

Example:

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. Create an object to hold your values. Create an object such as a struct or a class to hold your values and return the object in your function.

Example:

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

The method you choose will ultimately depend on the situation.

like image 42
intcreator Avatar answered Oct 21 '22 08:10

intcreator