Transpose a Matrix
แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Transpose a Matrix
Transpose a Matrix คืออะไร?
แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Transpose a Matrix
แก้โจทย์ Transpose a Matrix ด้วย code C และ C++ ที่รันได้
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
int main(void) {
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
// Visit columns first to print the transposed shape.
for (int column = 0; column < 3; ++column) { for (int row = 0; row < 2; ++row) printf("%s%d", row ? " " : "", matrix[row][column]); puts(""); }
}
1 4
2 5
3 6
C++
main.cpp
#include <array>
#include <iostream>
int main() {
std::array<std::array<int, 3>, 2> matrix{{{{1, 2, 3}}, {{4, 5, 6}}}};
// Visit columns first to print the transposed shape.
for (size_t column = 0; column < 3; ++column) { for (size_t row = 0; row < 2; ++row) std::cout << (row ? " " : "") << matrix[row][column]; std::cout << '\n'; }
}
1 4
2 5
3 6
เปรียบเทียบ C และ C++
เปรียบเทียบ implementation ของ C และ C++ จากนั้นเปลี่ยน input และทดสอบ edge case เพิ่มเติม
C
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation