本文介绍C++语言中,一个函数返回两个及以上、同类型或不同类型的返回值的方法。
对于C++而言,其不能像Python等语言一样在一个函数中返回多个值;但是我们也会经常遇到需要返回两个甚至更多个值的需求。针对这种情况,我们可以通过pair、tuple(元组)等数据结构,实现C++函数返回两个或多个返回值。本文就以pair为例,介绍二者的具体用法。
一、pair<>
首先,我们需要将C++函数的类型定义为pair<>,其中<>内为两个返回值各自的数据类型。例如,如以下代码所示,我们定义了函数A,函数类型为pair<double**, double*>,表示这一函数的返回值有两个,且两个返回值的数据类型分别为double**与double*。
pair<double**, double*> A(double** pafScanline)
{
// 这里是函数的代码部分
// ...
return make_pair(a, b);
}
其中,在函数的返回值部分,我们需要基于make_pair()函数,将数据类型分别为double**与double*的两个变量放在一起,形成pair这一结构,再进行返回。
其次,以上pair、make_pair()等都是定义在std这一命名空间内的,因此需要首先声明一下这一命名空间;再次,在调用这一函数前,我们首先需要定义一个pair <double**, double*>类型的变量,并将函数的返回值赋给它。
随后,通过.first与.second命令,分别获取pair<double**, double*>中的两个变量。
至此,我们即实现了通过一个C++函数返回两个返回值的方法。
二、tuple<>
如果需要返回三个或更多的返回值,则可以基于tuple(元组)这一数据结构,用类似于上述操作的方法来实现。
引用头文件
#include <tuple>
2. Tuple初始化
std::tuple的初始化可以通过构造函数实现。
// Creating and Initializing a tuple
std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };
这种初始化方式要定义各个元素的数据类型,比较繁琐,C++11也提供了另外一种方式std::make_tuple。
3. std::make_tuple
// Creating a tuple using std::make_tuple
auto result2 = std::make_tuple( 7, 9.8, "text" );
这种初始化方式避免需要逐个指定元素类型的问题,自动化实现各个元素类型的推导。
完整例子一:
#include <iostream>
#include <tuple>
#include <string>
int main()
{
// Creating and Initializing a tuple
std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };
// Compile error, as no way to deduce the types of elements in tuple
//auto result { 22, 19.28, "text" }; // Compile error
// Creating a tuple using std::make_tuple
auto result2 = std::make_tuple( 7, 9.8, "text" );
// std::make_tuple automatically deduced the type and created tuple
// Print values
std::cout << "int value = " << std::get < 0 > (result2) << std::endl;
std::cout << "double value = " << std::get < 1 > (result2) << std::endl;
std::cout << "string value = " << std::get < 2 > (result2) << std::endl;
return 0;
}
输出:
<strong>int</strong> value = 7
<strong>double</strong> value = 9.8
string value = text
完整例子二:
#include <iostream>
#include <tuple>
#include <functional>
std::tuple<int, int> f() // this function returns multiple values
{
int x = 5;
return std::make_tuple(x, 7); // return {x,7}; in C++17
}
int main()
{
// heterogeneous tuple construction
int n = 1;
auto t = std::make_tuple(10, "Test", 3.14, std::ref(n), n);
n = 7;
std::cout << "The value of t is " << "("
<< std::get<0>(t) << ", " << std::get<1>(t) << ", "
<< std::get<2>(t) << ", " << std::get<3>(t) << ", "
<< std::get<4>(t) << ")\n";
// function returning multiple values
int a, b;
std::tie(a, b) = f();
std::cout << a << " " << b << "\n";
}
输出:
The value of t is (10, Test, 3.14, 7, 1)
5 7