ตรวจพาลินโดรม
ตรวจว่าคำอ่านจากหน้าไปหลังและหลังไปหน้าเหมือนกันหรือไม่
ตรวจพาลินโดรม คืออะไร?
พาลินโดรมไม่เปลี่ยนเมื่อกลับลำดับตัวอักษร
ประเด็นสำคัญ
- เปิด compiler warning และแก้ทุกคำเตือน
- รู้ type และ lifetime ของทุกค่า
- ตรวจ input และขอบเขต array ให้ชัดเจน
ตัวอย่างโค้ด C และ C++
main.c
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "level"; size_t length = strlen(text); int palindrome = 1;
// Compare characters mirrored around the center.
for (size_t i = 0; i < length / 2; ++i)
if (text[i] != text[length - 1 - i]) { palindrome = 0; break; }
printf("%s is %sa palindrome\n", text, palindrome ? "" : "not ");
}
level is a palindrome
C++
main.cpp
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string text = "level";
// equal compares the first half with a reversed view.
bool palindrome = std::equal(text.begin(), text.begin() + text.size() / 2, text.rbegin());
std::cout << text << " is " << (palindrome ? "" : "not ") << "a palindrome\n";
}
level is a palindrome
เปรียบเทียบ C และ C++
เทียบตำแหน่งที่สมมาตรกันและหยุดที่ตรงกลาง เพราะแต่ละคู่ต้องตรวจครั้งเดียว
C
C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน
C++
C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า
แบบฝึกหัด
รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา
- เพิ่ม input ผิดและค่าขอบเขต
- Compile ด้วย -Wall -Wextra -Wpedantic
- แยก declaration และ implementation
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด