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

การจัดการชนิดอาร์เรย์ (Array Type Manipulation) ใน C++

Type Traits สำหรับอาร์เรย์

C++ มี `` ที่ให้ฟังก์ชันตรวจสอบและจัดการชนิดอาร์เรย์ได้ใน compile-time

1. std::is_array - ตรวจสอบว่าเป็นอาร์เรย์หรือไม่

#include <type_traits>
#include <iostream>
#include <array>
#include <string>
using namespace std;

int main() {
    cout << boolalpha;
    cout << "int is array? " << is_array<int>::value << endl;           // false
    cout << "int[6] is array? " << is_array<int[6]>::value << endl;       // true
    cout << "int[2][3] is array? " << is_array<int[2][3]>::value << endl; // true
    cout << "string is array? " << is_array<string>::value << endl;       // false
    cout << "char[4] is array? " << is_array<char[4]>::value << endl;     // true
    cout << "std::array<int,5> is array? " << is_array<array<int,5>>::value << endl; // false!
    return 0;
}

หมายเหตุ: `std::array` ไม่ถือเป็น array ตามมุมมองของ is_array (เป็น class template)

2. std::is_same - ตรวจสอบชนิดเหมือนกัน

cout << "int[3] == int[4]? " << is_same<int[3], int[4]>::value << endl;     // false (ขนาดต่าง)
cout << "int[5] == int[5]? " << is_same<int[5], int[5]>::value << endl;     // true
cout << "int[3] == int[3][4]? " << is_same<int[3], int[3][4]>::value << endl; // false
cout << "int[5] == char[5]? " << is_same<int[5], char[5]>::value << endl;   // false

3. std::rank - หาจำนวนมิติ (Rank)

cout << "int rank: " << rank<int>::value << endl;              // 0 (scalar)
cout << "int[5] rank: " << rank<int[5]>::value << endl;        // 1
cout << "int[2][2] rank: " << rank<int[2][2]>::value << endl;    // 2
cout << "int[2][3][4] rank: " << rank<int[2][3][4]>::value << endl; // 3

4. std::extent - หาขนาดของมิติที่ระบุ

// อาร์เรย์ int[2][45][5]
cout << "Dim 0: " << extent<int[2][45][5], 0>::value << endl; // 2
cout << "Dim 1: " << extent<int[2][45][5], 1>::value << endl; // 45
cout << "Dim 2: " << extent<int[2][45][5], 2>::value << endl; // 5
cout << "Dim 3: " << extent<int[2][45][5], 3>::value << endl; // 0 (ไม่มี)

5. std::remove_extent - ลบมิติแรกออก

// int[20][10][30] → ลบมิติแรก → int[10][30]
cout << "Rank after remove_extent: " 
     << rank<remove_extent<int[20][10][30]>::type>::value << endl; // 2
cout << "New dim 0 size: " 
     << extent<remove_extent<int[20][10][30]>::type, 0>::value << endl; // 10

6. std::remove_all_extents - ลบมิติทั้งหมด

// int[20][10][30] → ลบทุกมิติ → int
cout << "Rank after remove_all_extents: " 
     << rank<remove_all_extents<int[20][10][30]>::type>::value << endl; // 0

สรุปตาราง

Traitคืนค่าตัวอย่าง
is_array<T>boolis_array<int[5]>::value == true
rank<T>size_t (จำนวนมิติ)rank<int[2][3]>::value == 2
extent<T, N>size_t (ขนาดมิติ N)extent<int[2][3], 0>::value == 2
remove_extent<T>::typeType (ลบมิติแรก)int[2][3] → int[3]
remove_all_extents<T>::typeType (ลบทุกมิติ)int[2][3] → int