แบบฝึกหัด C/C++ สำหรับผู้เริ่มต้น

Find the Second Largest Value

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Find the Second Largest Value

Find the Second Largest Value คืออะไร?

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Find the Second Largest Value

แก้โจทย์ Find the Second Largest Value ด้วย code C และ C++ ที่รันได้

ประเด็นสำคัญ

  • เปิด compiler warning และแก้ทุกคำเตือน
  • รู้ type และ lifetime ของทุกค่า
  • ตรวจ input และขอบเขต array ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <limits.h>
#include <stdio.h>
int main(void) {
    int values[] = {7, 23, 12, 23, 9}, first = INT_MIN, second = INT_MIN;
    // Maintain the two largest distinct values.
    for (int i = 0; i < 5; ++i) { int value = values[i]; if (value > first) { second = first; first = value; } else if (value > second && value != first) second = value; }
    printf("second=%d\n", second);
}
ผลลัพธ์ที่คาดหวัง
second=12
C++
รันโค้ด →
main.cpp
#include <iostream>
#include <limits>
#include <vector>
int main() {
    std::vector values{7, 23, 12, 23, 9}; int first = std::numeric_limits<int>::min(), second = first;
    // Maintain the two largest distinct values.
    for (int value : values) { if (value > first) { second = first; first = value; } else if (value > second && value != first) second = value; }
    std::cout << "second=" << second << '\n';
}
ผลลัพธ์ที่คาดหวัง
second=12

เปรียบเทียบ 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