การเก็บข้อมูล Triplet (3 ค่า) ใน Vector ใน C++
เพื่อเก็บค่า 3 ค่าในองค์ประกอบเดียวของ vector สร้าง struct (user-defined type) แล้วสร้าง vector ของ struct นั้น
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
struct Test {
int x, y, z;
};
int main() {
// สร้าง vector ของ user-defined structure
vector<Test> myvec;
// เพิ่มข้อมูล
myvec.push_back({2, 31, 102});
myvec.push_back({5, 23, 114});
myvec.push_back({9, 10, 158});
int s = myvec.size();
for (int i = 0; i < s; i++) {
cout << myvec[i].x << ", " << myvec[i].y << ", " << myvec[i].z << endl;
}
return 0;
}
ผลลัพธ์
2, 31, 102 5, 23, 114 9, 10, 158
วิธีอื่นๆ
- ใช้
std::tuple<int, int, int>หรือstd::array<int, 3>(C++11 ขึ้นไป) - ใช้
std::pair<int, std::pair<int, int>>(ซ้อน pair) - Struct ให้ความหมายชัดเจนที่สุด (semantic clarity)
ข้อดีของ Struct
- ตั้งชื่อฟิลด์ได้ (x, y, z) อ่านโค้ดเข้าใจง่าย
- เพิ่มเมธอด/constructor ได้
- รองรับการทำงานกับ algorithm ทั่วไปของ STL