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

วิธีพิมพ์มิติของอาร์เรย์หลายมิติใน C++

นี่คือโปรแกรม C++ สำหรับพิมพ์มิติของอาร์เรย์ที่กำหนด

อัลกอริธึม

ใช้ template function เพื่อหาขนาดของมิติปัจจุบัน แล้วเรียกซ้ำ (recursive) จนถึงมิติสุดท้าย

โค้ดตัวอย่าง

#include <iostream>
using namespace std;

// Base case: 1D array
template <typename T, size_t N>
void printDimensionsOfArray(const T (&a)[N]) {
    cout << N;
}

// Recursive case: 2D+ array
template <typename T, size_t N, size_t M>
void printDimensionsOfArray(const T (&a)[N][M]) {
    cout << "Dimensions of the Array is: " << N << " x ";
    printDimensionsOfArray(a[0]); // เรียกซ้ำกับมิติถัดไป
}

int main() {
    int a[6][7];
    printDimensionsOfArray(a);
    return 0;
}

ผลลัพธ์

Dimensions of the Array is: 6 x 7

ขยายสำหรับ 3 มิติขึ้นไป: เพิ่ม template overload อีกชั้น

template <typename T, size_t N, size_t M, size_t K>
void printDimensionsOfArray(const T (&a)[N][M][K]) {
    cout << "Dimensions of the Array is: " << N << " x " << M << " x ";
    printDimensionsOfArray(a[0]);
}

ข้อจำกัด: ทำงานได้เฉพาะกับอาร์เรย์แบบคงที่ (fixed-size array) ที่รู้ขนาดตอนคอมไพล์ ไม่ทำงานกับ pointer หรือ dynamic array