ในบทเรียนนี้ เราจะอธิบาย pair ใน C++ STL
Pair คืออะไร?
pair เป็น Container ใน Header <utility> เก็บค่า 2 ค่า รวม Type ต่างกันได้ ใช้จับคู่ข้อมูล 2 ชิ้น
สมาชิกของ Pair
first− ค่าแรกsecond− ค่าที่สอง
ตัวอย่าง
#include <iostream>
#include <utility>
using namespace std;
int main() {
// Initialization แบบต่างๆ
pair<int, char> p1;
p1.first = 100;
p1.second = 'G';
pair<string, double> p2("Pi", 3.14159);
auto p3 = make_pair(10, 20); // Type Deduction
cout << p1.first << " " << p1.second << endl;
cout << p2.first << " = " << p2.second << endl;
cout << p3.first << ", " << p3.second << endl;
return 0;
}
ผลลัพธ์
100 G Pi = 3.14159 10, 20
การใช้งานทั่วไป
- Return ค่า 2 ค่าจาก Function
- เก็บใน Vector/Map:
vector<pair<int,int>> - Sort Vector of Pair (เรียงตาม First แล้ว Second อัตโนมัติ)
Structured Binding (C++17)
auto [x, y] = make_pair(10, 20); cout << x << " " << y; // 10 20