ใน C หรือ C++ เราไม่สามารถคืนค่ามากกว่าหนึ่งค่าจากฟังก์ชัน ในการคืนค่าหลายค่า เราต้องจัดเตรียมพารามิเตอร์เอาต์พุตพร้อมกับฟังก์ชัน ที่นี่เราจะเห็นวิธีอื่นในการคืนค่าหลายค่าจากฟังก์ชันโดยใช้ทูเพิลและจับคู่ STL ใน C++
Tuple เป็นวัตถุที่สามารถเก็บคอลเล็กชันขององค์ประกอบได้ โดยแต่ละองค์ประกอบสามารถมีได้หลายประเภท
ทั้งคู่สามารถสร้างชุดของค่าสองค่าซึ่งอาจเป็นประเภทต่างๆ โดยพื้นฐานแล้วทั้งคู่เป็นทูเพิลชนิดพิเศษ ซึ่งอนุญาตให้ใช้เพียงสองค่าเท่านั้น
เรามาดูตัวอย่างกัน โดยเราจะมาดูกันว่าทูเพิลและคู่กันทำงานอย่างไร
ตัวอย่าง
#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 ถูกกำหนดเป็น (เป็นโมฆะ*)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 *)
เราสามารถใช้ nullptr ได้ทุกที่ที่คาดว่าจะเป็น NULL เช่นเดียวกับค่า NULL ค่า nullptr สามารถแปลงเป็นพอยน์เตอร์ประเภทใดก็ได้ แต่สิ่งนี้ไม่สามารถแปลงเป็นอินทิกรัลได้โดยปริยาย เช่น NULL