使用C++中的Tuple和Pair从函数返回多个值


在C或C++中,我们不能从函数返回多个值。要返回多个值,我们必须为函数提供输出参数。在这里,我们将看到另一种使用C++中的tuple和pair STL从函数返回多个值的方法。

Tuple是一个能够保存元素集合的对象,其中每个元素可以是不同类型。

Pair可以创建一个由两个值组成的集合,这两个值可以是不同类型。Pair基本上是一种特殊的tuple,只允许两个值。

让我们来看一个例子,我们将看到tuple和pair是如何工作的。

示例

#include<iostream>
#include<tuple>
#include<utility>
using namespace std;
tuple<int, string, char> my_function_tuple(int x, string y) {
   return make_tuple(x, y, 'A'); // make tuples with the values and return
}
std::pair<int, string> my_function_pair(int x, string y) {
   return std::make_pair(x, y); // make pair with the values and return
}
main() {
   int a;
   string b;
   char c;
   tie(a, b, c) = my_function_tuple(48, "Hello"); //unpack tuple
   pair<int, string> my_pair = my_function_pair(89,"World"); //get pair from function
   cout << "Values in tuple: ";
   cout << "(" << a << ", " << b << ", " << c << ")" << endl;
   cout << "Values in Pair: ";
   cout << "(" << my_pair.first << ", " << my_pair.second << ")" << endl;
}

输出

Values in tuple: (48, Hello, A)
Values in Pair: (89, World)

上述程序的问题是什么?NULL通常定义为(void*)0。我们允许将NULL转换为整型。因此,my_func(NULL)的函数调用是模糊的。

如果我们使用nullptr代替NULL,我们将得到如下结果:

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

#include<iostream>
using namespace std;
int my_func(int N) { //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(nullptr); //it will call my_func(char *), but will generate compiler error
}

输出

calling function my_func(char *)

我们可以在所有期望使用NULL的地方使用nullptr。与NULL一样,nullptr也可以转换为任何指针类型。但这不像NULL那样可以隐式转换为整型。

更新于:2019年7月30日

3K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告