นี่คือโปรแกรม C++ เรียบง่ายสำหรับสร้างอาร์เรย์ 2 มิติแบบไดนามิกภายในคลาสเพื่อพิมพ์องค์ประกอบของอาร์เรย์ (หมายเหตุ: โค้ดต้นฉบับเป็นอาร์เรย์ 1 มิติในคลาส ไม่ใช่ 2 มิติ จึงปรับแก้ให้เป็น 2 มิติจริง)
อัลกอริธึม
- สร้างคลาส
Arrและประกาศขนาดอาร์เรย์ - ภายในคลาส เริ่มต้นองค์ประกอบทั้งหมดด้วยลูป for
- พิมพ์องค์ประกอบทั้งหมด
โค้ดตัวอย่าง (ปรับปรุงเป็น 2D Array จริง)
#include <iostream>
#include <memory>
using namespace std;
class Matrix {
private:
int rows, cols;
unique_ptr<unique_ptr<int[]>[]> data; // 2D array บน heap
public:
Matrix(int r, int c, int initVal = 0) : rows(r), cols(c) {
data = make_unique<unique_ptr<int[]>[]>(rows);
for (int i = 0; i < rows; ++i) {
data[i] = make_unique<int[]>(cols);
for (int j = 0; j < cols; ++j)
data[i][j] = initVal;
}
}
int& operator()(int r, int c) {
if (r < 0 || r >= rows || c < 0 || c >= cols) {
throw out_of_range("Matrix index out of bounds");
}
return data[r][c];
}
int getRows() const { return rows; }
int getCols() const { return cols; }
};
int main() {
Matrix m(3, 4); // 3 rows, 4 cols
for (int i = 0; i < m.getRows(); ++i)
for (int j = 0; j < m.getCols(); ++j)
m(i, j) = i * 10 + j;
cout << "Matrix elements:" << endl;
for (int i = 0; i < m.getRows(); ++i) {
for (int j = 0; j < m.getCols(); ++j)
cout << m(i, j) << " ";
cout << endl;
}
return 0; // unique_ptr ลบหน่วยความจำอัตโนมัติ
}
ผลลัพธ์
Matrix elements: 0 1 2 3 10 11 12 13 20 21 22 23
วิธีแบบดั้งเดิม (Legacy): ใช้ new int*[rows] แล้วลูป new int[cols] และต้อง delete[] เอง (ดูบทความ 1004082802) วิธีด้านบนใช้ unique_ptr จัดการหน่วยความจำอัตโนมัติ (RAII) ปลอดภัยกว่า