使用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,我們將得到如下結果:
示例
#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那樣可以隱式轉換為整型。
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP