在C或C ++中,我们不能从一个函数返回多个值。要返回多个值,我们必须为输出参数提供函数。在这里,我们将看到另一种在C ++中使用元组和STL对从函数返回多个值的方法。
元组是一个能够容纳元素集合的对象,其中每个元素可以具有不同的类型。
该对可以构成两个值的集合,这两个值可以是不同的类型。该对基本上是一种特殊的元组,其中只允许两个值。
让我们看一个例子,在这里我们将看到元组和对如何工作。
#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,我们将得到如下结果-
#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之类的整数类型。