Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Return ค่าหลายค่าจากฟังก์ชันด้วย Tuple และ Pair ใน C++

C++ ไม่รองรับ multiple return values โดยตรง แต่ใช้ std::tuple (หลายค่า) และ std::pair (2 ค่า) จาก <tuple> และ <utility>

Tuple

#include <tuple> #include <string>
using namespace std;

tuple<int, string, char> func_tuple(int x, string y) {
    return make_tuple(x, y, 'A');
}

int a; string b; char c;
tie(a, b, c) = func_tuple(48, "Hello"); // unpack
cout << a << b << c; // 48 Hello A

Pair

#include <utility>
pair<int, string> func_pair(int x, string y) {
    return make_pair(x, y);
}

auto p = func_pair(89, "World");
cout << p.first << p.second; // 89 World

C++17 Structured Bindings (แนะนำ)

auto [a, b, c] = func_tuple(48, "Hello");
auto [x, y] = func_pair(89, "World");

Tuple เหมาะสำหรับ 3+ ค่า Pair สำหรับ 2 ค่า Structured bindings ทำให้โค้ดสะอาดกว่า