How to return multiple values from a function in C++

6 Answers

0 votes
#include <iostream>
#include <string>

// This function returns a struct containing three values.
// The struct is defined *inside* the function, which is allowed in C++.
// The return type is deduced automatically using 'auto'.
auto f() {
    // Local struct definition
    struct values {
        int a, b;        // two integers
        std::string s;   // one string
    };

    // Return an instance of the struct using brace initialization
    return values{12, 837, "c++"};
}

int main() {
    // Structured binding: C++17 feature.
    // It "unpacks" the returned struct into three separate variables.
    auto [value1, value2, value3] = f();

    std::cout << value1 << ", " << value2 << ", " << value3;
}


/*
run:

12, 837, c++

*/

 



answered May 14, 2021 by avibootz
edited 1 day ago by avibootz
0 votes
// Using std::tuple

#include <iostream>
#include <tuple>

std::tuple<int, double, std::string> getValues() {
    return {42, 3.14, "hello"};
}

int main() {
    auto [x, y, z] = getValues();
    
    std::cout << "x = " << x << ", y = " << y << ", z = " << z << "\n";
}



/* 
run:

x = 42, y = 3.14, z = hello

*/

 



answered May 14, 2021 by avibootz
edited 1 day ago by avibootz
0 votes
#include <iostream>

std::pair<int, int> f() {
    std::pair<int, int> pr;

    pr.first = 23;
    pr.second = 848;
    
    return pr;
}


int main() {
    auto pr = f();
    
    std::cout << pr.first << " " << pr.second;

    return 0;
}




/*
run:

23 848

*/

 



answered May 14, 2021 by avibootz
0 votes
// Using Output Parameters (References)

#include <iostream>

void compute(int a, int b, int &sum, int &product) {
    sum = a + b;
    product = a * b;
}

int main() {
    int s, p;
    
    compute(3, 4, s, p);
    
    std::cout << "sum = " << s << ", product = " << p << "\n";
}



/* 
run:

sum = 7, product = 12

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz
0 votes
// Using std::pair
 
#include <iostream>

std::pair<int, int> getPair() {
    return {10, 20};
}

int main() {
    auto result = getPair();
    
    std::cout << "a = " << result.first << ", b = " << result.second << "\n";

}


/* 
run:

a = 10, b = 20


*/

 



answered 1 day ago by avibootz
0 votes
// Using a Custom Struct

#include <iostream>

struct Data {
    int id;
    double score;
};

Data getData() {
    return {7, 99.5};
}

int main() {
    Data d = getData();
    
    std::cout << "id = " << d.id << ", score = " << d.score << "\n";
}


/* 
run:

id = 7, score = 99.5

*/

 



answered 1 day ago by avibootz
...