C++
C++处理多返回值的4种方法
文章目录
概述
在C++中,如果有一个函数需要返回多个相同类型的值,可以用数组或者vector。但如果是返回多个类型不同的值呢?这里介绍4种常用的方法。
方法1:自己创建一个结构体,让返回值为这个结构体类型即可。(当然,创建一个class也可以,但只有纯数据的情况下,我更喜欢用struct。总之不管用什么,本质上就是自己创建了一个类型。)
方法2:函数参数使用引用传递
方法3:使用std::tuple返回3个或以上的返回值
方法4:如果返回值只有两个,可以使用std::pair返回
详细介绍
假设现在有一个GetInfo函数,需要同时返回一个string值、一个int值、一个float值。4种方法的处理如下。
方法1:自己创建一个结构体,让返回值为这个结构体类型
代码如下(示例):
struct MyStruct
{
std::string s_name;
int s_age;
float s_height;
};
MyStruct GetInfo()
{
//模拟从某处获取这些值
MyStruct my0 = {"Bob",20,1.8f};
return my0;
}
说明:这种方法本质就是自己新建了一个类型,很灵活。当然,你用class实现也可以~~
方法2:函数参数使用引用传递
代码如下(示例):
void GetInfo(std::string& out_name, int& out_age, float& out_height)
{
out_name = "Bob";
out_age = 20;
out_height = 1.8f;
}
int main()
{
string name;
int age;
float height;
GetInfo(name, age, height);
}
方法3:使用std::tuple返回3个或以上的返回值
- std::make_tuple可以创建tuple
- 使用std::get<index>(tuple_name)获取tuple的元素(见代码写法1)
- C++17及以上的版本中,可以使用结构化绑定获取元素(见代码写法2)
代码如下(示例):
#include <tuple>
#include <string>
std::tuple<std::string, int, float> GetInfo_tuple()
{
return std::make_tuple("Bob", 20, 1.8f);
}
int main()
{
//写法1
std::tuple<std::string, int, float> out = GetInfo_tuple();
std::string name = std::get<0>(out);
int age= std::get<1>(out);
float height= std::get<2>(out);
//写法2
auto [name1,age1,height1]=GetInfo_tuple();
}
方法4:使用std::pair返回两个返回值
- 只能用于两个返回值的情况
- std::make_pair可以创建pair
- 获取pair元素:
(1)std::get<index>(pair_name)
(2)pair_name.first/second
(3)结构化绑定
代码如下(示例):
#include <utility>
#include <string>
std::pair<std::string, int> GetInfo_pair()
{
return std::make_pair("Bob", 20);
}
int main()
{
std::pair<std::string, int> out_pair = GetInfo_pair();
std::string name = out_pair.first; // std::get<0>(out_pair);
int age = out_pair.second; //std::get<1>(out_pair);
}