+ 2
Returning multiple variables in c/cpp
Is it possible to return multiple variables in c/cpp without using pointer? And if it is, how?
2 Antworten
+ 12
Yes you can do that by using tuple. Below is an implementation of it.
#include <iostream>
#include <tuple>
using namespace std;
tuple<int, int> swap(int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
return make_tuple(num1, num2);
}
int main() {
int num1 = 10, num2 = 20;
cout << "num1: " << num1 << ", num2: " << num2 << endl;
tie(num1, num2) = swap(num1, num2);
cout << "num1: " << num1 << ", num2: " << num2 << endl;
return 0;
}
Edit: You can also return multiple values of different data types from a function using tuple.
+ 4
And now with C++17's structured bindings, you can declare multiple variables together and read values from functions returning tuples or pairs on the fly.
Eg :
auto parse_date(string s)
{
auto p1 = s.find('/'), p2 = s.find('/',p1+1);
return make_tuple(stoi(s.substr(0,p1)), stoi(s.substr(p1,p2-p1)), stoi(s.substr(p2)));
}
int main()
{
auto [day,month,year] = parse_date("19/02/2019");
}