Motivation
Python supports the concept of multiple return values since its first version.
C++ introduced the concept in C++11. Let’s have a look how it works:
How to use it
- You need to include the header
include <tuple>
- You have to declare return parameter of your function e.g.
std::tuple<int, int>
- You use the function make_tuple:
return std::make_tuple(x, y);
- On the caller side you need to tie the return values to local variables e.g.
std::tie(x_pos, y_pos)
That’s all!
Example Code
#include
#include
#include
std::tuple<double, double> calculate_mean_and_variance(std::vector measurements)
{
double sum = 0.0;
for (double num : measurements) {
sum += num;
}
double _mean = sum / measurements.size();
double sq_sum = 0.0;
for (double num : measurements) {
sq_sum += (num - _mean) * (num - _mean);
}
double variance = sq_sum / measurements.size();
return std::make_tuple(_mean, variance);
}
int main()
{
std::vector measurements = { 1, 2, 3, 4 };
double mean, variance;
std::tie(mean, variance) = calculate_mean_and_variance(measurements);
std::cout << mean << ", " << variance << std::endl;
return 0;
}