Thuta Learning
C++
ExercisesProgrammingအခြေခံ

Exercises: OOP & STL Challenge

C++သင်ခန်းစာ 3540 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Private data နဲ့ checked constructor ပါတဲ့ class ကို ရေးပြီး std::vector ထဲ သိမ်းနိုင်ဖို့
  • & နဲ့ * ရဲ့ အဓိပ္ပာယ်ကို declaration နဲ့ expression နှစ်နေရာမှာ ခွဲပြောနိုင်ဖို့
  • Pointer ကနေ object ကို ပြောင်းပြီး dereference မလုပ်ခင် nullptr ကို စစ်နိုင်ဖို့
  • Function ကို caller ရဲ့ vector ကို တကယ်ပြောင်းစေတဲ့ reference parameter နဲ့ copy ပေါ်မှာပဲ အလုပ်လုပ်တဲ့ by-value ကို ခွဲခြားနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

ဒီ exercise set က warm-up ထက် ပိုခက်ပါတယ်၊ အကြောင်းက အရင် chapter တွေက အကြောင်းအရာ သုံးမျိုးကို တစ်ပြိုင်နက် သုံးရလို့ပါ။ Class နဲ့ object၊ std::vector၊ pointer နဲ့ reference ပါ။ သူတို့ကို သီးခြားစီ နားလည်ထားပြီးသားဆိုရင်တောင် ပေါင်းသုံးတဲ့အခါ ရောထွေးတတ်ပါတယ်။ အဓိကအကြောင်းက & နဲ့ * ဆိုတဲ့ သင်္ကေတတွေက နေရာကို လိုက်ပြီး အဓိပ္ပာယ် ကွဲသွားလို့ပါ။

စာကြည့်တိုက်ကို စဉ်းစားကြည့်ပါ။ Book object က စာအုပ်တစ်အုပ်၊ vector က စင်၊ pointer က "စင်ရဲ့ ဘယ်နေရာမှာ" ဆိုတဲ့ ကတ်ပြားတစ်ခု၊ reference က စာအုပ်ကို နောက်နာမည်တစ်ခုနဲ့ ခေါ်တာ၊ by-value pass လုပ်တာက စာအုပ်ကို photocopy လုပ်ပြီး ပေးတာပါ။ Photocopy ပေါ်မှာ မှတ်စုရေးရင် မူရင်းစာအုပ်မှာ ဘာမှ မပါသလို အဲဒီ ဥပမာက ဒီ lesson ရဲ့ အဓိက ပြဿနာပါပဲ။

Problem → Why → Solution

ပြဿနာ: ပြောင်းမယ်လို့ ထင်ပြီး ဘာမှ မပြောင်းတဲ့ code

အောက်က draft မှာ slip နှစ်ခု ရှိပါတယ်။ ပထမတစ်ခုက doubleValues() က vector ကိုလည်း value နဲ့ လက်ခံပြီး loop variable int n ကိုလည်း value နဲ့ ယူထားတာပါ။ Copy နှစ်ထပ်ပေါ်မှာ အလုပ်လုပ်လို့ main() ထဲက nums က 1 2 3 အတိုင်း ကျန်ပါတယ်။ ဒီအပိုင်းက compile ဖြစ်ပြီး g++ -Wall က warning: variable 'n' set but not used လို့ တစ်ခုပဲ ပေးပါတယ်။ Error မဟုတ်ပါဘူး၊ warning ကို ဖတ်မှ သတိထားမိမှာပါ။

ဒုတိယ slip က နောက်ဆုံး line ပါ။ ptr = 100; လို့ ရေးတာက score ကို ပြောင်းမယ်လို့ ရည်ရွယ်ပေမယ့် ptr ကိုယ်တိုင်ကို number တစ်ခု ပေးလိုက်တာပါ။ ဒါကတော့ g++ က error: invalid conversion from 'int' to 'int*' လို့ ငြင်းပါတယ်။ ဒီအမှားကို ပြင်ပြီးရင်တောင် ပထမ slip က ဆက်ရှိနေမယ့် အချက်ကို သတိထားပါ။

draft.cpp
void doubleValues(std::vector<int> nums) {  // no &: the function gets a copy
    for (int n : nums) {                    // no &: n is a copy of each element
        n *= 2;
    }
}

int main() {
    std::vector<int> nums = {1, 2, 3};
    doubleValues(nums);
    for (int n : nums) {
        std::cout << n << ' ';  // prints 1 2 3: nothing was doubled
    }
    std::cout << '\n';

    int score = 90;
    int* ptr = &score;
    ptr = 100;  // meant: *ptr = 100
}

ဘာကြောင့် ကွဲပြားသွားတာလဲ

C++ မှာ & ရဲ့ အဓိပ္ပာယ်က ရှေ့က နေရာကို လိုက်ပြီး ပြောင်းပါတယ်။ std::vector<int>& လို့ type ထဲမှာ ရေးရင် "ဒီ object ကို နောက်နာမည်တစ်ခုနဲ့ ခေါ်တာ" ဖြစ်ပြီး &score လို့ expression ထဲမှာ ရေးရင် "score ရဲ့ address" ဖြစ်ပါတယ်။ * ကလည်း int* မှာ pointer type ကို ကြေညာပြီး *ptr မှာ pointer ညွှန်ရာ object ကို ရောက်စေပါတယ်။ ဒီ lesson ရဲ့ bug အားလုံးက သင်္ကေတကို မှားဖတ်တာကနေ လာပါတယ်။

Core concept: object၊ address နဲ့ နာမည်

Task သုံးခုလုံးက "ဒီ code က ဘယ် object ကို တကယ် ထိနေတာလဲ" ဆိုတဲ့ မေးခွန်းတစ်ခုတည်းကို မေးပါတယ်။ ဖြေဖို့ အရင်ဆုံး & နဲ့ * က နေရာအလိုက် ဘာကို ဆိုလိုလဲ ဆိုတာ ခွဲသိထားဖို့ လိုပါတယ်။

ရေးပုံအဓိပ္ပာယ်
int* pDeclaration: p က int တစ်ခုကို ညွှန်တဲ့ pointer
&scoreExpression: score ရဲ့ address
*pExpression: p ညွှန်ရာ int (ဖတ်လို့၊ ရေးလို့ရ)
std::vector<int>& vDeclaration: caller ရဲ့ vector ရဲ့ နောက်နာမည်
const Book& bDeclaration: ဖတ်ရုံသာ နောက်နာမည်၊ copy မကူး

၁။ Task 1: rule ကို စောင့်တဲ့ Book class

title_ နဲ့ price_ ကို private ထားပြီး constructor မှာ price အနုတ်ဆိုရင် std::invalid_argument throw လုပ်ပါတယ်။ vector<Book> က Book တစ်အုပ်ချင်းရဲ့ copy ကို သိမ်းပါတယ်၊ ဒါကြောင့် push_back(Book("Misprint", -3.0)) မှာ constructor က argument ကို တည်ဆောက်ရင်းနဲ့ throw လုပ်ပြီး push_back ကို လုံးဝ မရောက်ပါဘူး၊ vector ထဲ မှားတဲ့ book မဝင်ပါဘူး။ Loop မှာတော့ const Book& b နဲ့ ဖတ်ပါ၊ book တစ်အုပ်ချင်းကို copy မကူးရတော့ပါဘူး။

၂။ Task 2: pointer ကနေ ပြောင်းပါ

int* ptr = &score; ပြီးရင် *ptr += 10 က ptr ညွှန်တဲ့ int ကို ပြောင်းလို့ score ကိုယ်တိုင် 100 ဖြစ်သွားပါတယ်။ ptr ကိုယ်တိုင်ကို ပြောင်းချင်ရင်တော့ ptr = &another လို့ ရေးပါတယ်၊ ဒါက ညွှန်ရာကို ပြောင်းတာပါ။ nullptr ကို ညွှန်နေတဲ့ pointer ကို dereference လုပ်တာက undefined behaviour မို့ *p မသုံးခင် p == nullptr ကို စစ်ပါ။ Address ကိုယ်တိုင်ကို print ထုတ်တာက run တိုင်း ကွာနိုင်လို့ test အတွက် ptr == &score လို နှိုင်းယှဉ်ချက်ကို သုံးပါ။

၃။ Task 3: reference ကနေ vector ကို ပြောင်းပါ

void doubleValues(std::vector<int>& nums) မှာ & ကြောင့် nums က caller ရဲ့ vector ကိုပဲ ညွှန်ပါတယ်။ Loop မှာလည်း for (int& n : nums) လို့ & ထပ်ထည့်မှ element တစ်ခုချင်းကို တိုက်ရိုက်ပြောင်းလို့ ရပါတယ်။ နေရာနှစ်ခုလုံးမှာ & လိုပါတယ်၊ တစ်ခုပဲ ထည့်ရင် မပြောင်းပါဘူး။ Example က doubleCopy() ကိုပါ ထည့်ထားလို့ by-value version မှာ ဘာဖြစ်လဲ ဆိုတာ output နဲ့ တိုက်ရိုက် မြင်ရပါတယ်။

၄။ Edge case တွေကို စစ်ပါ

vector အလွတ်အတွက် loop က တစ်ခါမှ မ run လို့ ဘာမှ မဖြစ်ပါဘူး၊ ဒါကလည်း မှန်ပါတယ်။ 0 နဲ့ အနုတ်ကိန်းတွေကို နှစ်ဆလုပ်တာလည်း မှန်ပါတယ်။ ဒါပေမဲ့ int ကို နှစ်ဆလုပ်ရာမှာ 1,073,741,823 ထက်ကြီးတဲ့ တန်ဖိုးက 32-bit int ကို ကျော်သွားပြီး signed overflow (undefined behaviour) ဖြစ်ပါတယ်။ ဒီ exercise မှာတော့ ဂဏန်းသေးလို့ ပြဿနာမရှိပေမယ့် လက်တွေ့ code မှာ ဒီ limit ကို သတိထားပါ။

Mental model: ဘယ် object ကို ထိနေလဲ
  1. & က type ထဲဆို နာမည်၊ expression ထဲဆို address
  2. *p က p ညွှန်တဲ့ object ကို ရောက်စေ
  3. Value နဲ့ pass = copy၊ မူရင်းမပြောင်း
  4. Dereference မလုပ်ခင် nullptr စစ်

Code တစ်ကြောင်းကို ဖတ်တိုင်း "ဒီ line က မူရင်း object ကိုလား၊ copy ကိုလား ထိနေတာ" လို့ မေးပါ။ ဒီမေးခွန်းက ဒီ lesson ရဲ့ bug အားလုံးကို ဖမ်းပါတယ်။

အခြေခံ ပုံစံ

cpp
class Thing {                          // private data, checked constructor
public:
    Thing(Type a, Type b);             // throws when the rule is broken
    Type getA() const { return a_; }   // const: reading never changes it
private:
    Type a_, b_;
};

void change(std::vector<int>& v);          // &: works on the caller's vector
void show(const std::vector<Thing>& v);    // const &: read only, no copy
int* p = &x;  *p = 5;                      // & takes an address, * follows it

Class က data ကို private ထားပြီး constructor မှာ စစ်ပါတယ်။ Function parameter မှာ & က caller ရဲ့ object ကို ပြောင်းဖို့၊ const & က ဖတ်ရုံအတွက်၊ pointer မှာ & က address ယူဖို့ နဲ့ * က အဲဒီ address က object ကို လိုက်ဖို့ ဖြစ်ပါတယ်။

Reference solution: class၊ pointer နဲ့ reference

အောက်က program က Task သုံးခုကို အစဉ်လိုက် ပြပါတယ်။ Task 1 က vector အလွတ်ကို အရင်ပြပြီး book သုံးအုပ်ထည့်ကာ ဈေးအနုတ်နဲ့ book တစ်အုပ်ကို ထည့်ကြည့်တာကို ငြင်းခံရတာ ပြပါတယ်။ Task 2 က address ကိုယ်တိုင်ကို print မထုတ်ဘဲ ptr == &score ဆိုတဲ့ နှိုင်းယှဉ်ချက်နဲ့ စစ်ပါတယ်။ Task 3 က doubleCopy() ကို အရင်ခေါ်ပြီး ဘာမှ မပြောင်းတာ ပြပြီးမှ doubleValues() ကို ခေါ်ပါတယ်။

oop_stl.cpp
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

// Task 1: a class that guards its own data.
class Book {
public:
    Book(std::string title, double price) : title_(std::move(title)), price_(price) {
        if (price_ < 0.0) {
            throw std::invalid_argument("price cannot be negative");
        }
    }

    const std::string& getTitle() const { return title_; }
    double getPrice() const { return price_; }

private:
    std::string title_;
    double price_;
};

void printBooks(const std::vector<Book>& books) {
    if (books.empty()) {
        std::cout << "  (no books)\n";
        return;
    }
    for (const Book& b : books) {
        const std::string price = std::format("${:.2f}", b.getPrice());
        std::cout << std::format("  {:<14}{:>8}\n", b.getTitle(), price);
    }
}

// Task 3: the & means "work on the caller's vector", not on a copy.
void doubleValues(std::vector<int>& nums) {
    for (int& n : nums) {
        n *= 2;
    }
}

void doubleCopy(std::vector<int> nums) {  // by value: only the copy changes
    for (int& n : nums) {
        n *= 2;
    }
}

void printInts(const std::string& label, const std::vector<int>& nums) {
    std::cout << "  " << label << ":";
    if (nums.empty()) {
        std::cout << " (empty)";
    }
    for (int n : nums) {
        std::cout << ' ' << n;
    }
    std::cout << '\n';
}

int main() {
    std::cout << "Task 1\n";
    std::vector<Book> books;
    printBooks(books);
    books.push_back(Book("C++ Basics", 8.5));
    books.push_back(Book("STL Guide", 12.0));
    books.push_back(Book("OOP in Depth", 15.75));
    try {
        books.push_back(Book("Misprint", -3.0));
    } catch (const std::invalid_argument& e) {
        std::cout << "  rejected Misprint: " << e.what() << '\n';
    }
    printBooks(books);

    std::cout << "Task 2\n";
    int score = 90;
    int* ptr = &score;
    std::cout << std::boolalpha << "  ptr holds the address of score: "
              << (ptr == &score) << '\n';
    *ptr += 10;  // change the int that ptr points to
    std::cout << "  *ptr = " << *ptr << ", score = " << score << '\n';
    int* nowhere = nullptr;
    if (nowhere == nullptr) {
        std::cout << "  nowhere is null, so it must not be dereferenced\n";
    }

    std::cout << "Task 3\n";
    std::vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    doubleCopy(nums);
    printInts("after doubleCopy", nums);
    doubleValues(nums);
    printInts("after doubleValues", nums);
    std::vector<int> mixed = {-3, 0, 4};
    doubleValues(mixed);
    printInts("negatives and zero", mixed);
    std::vector<int> empty;
    doubleValues(empty);
    printInts("empty vector", empty);
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Constructor with an initializer listBook(std::string title, double price) : title_(std::move(title)), price_(price) {

    Member နှစ်ခုကို initializer list နဲ့ တိုက်ရိုက် initialize လုပ်ပါတယ်။ Constructor body ထဲက if (price_ < 0.0) က ပြီးမှ စစ်ပြီး throw လုပ်လို့ မှားတဲ့ Book တစ်အုပ် ဘယ်တော့မှ မရှိလာပါဘူး။

  2. The rule that rejects bad datathrow std::invalid_argument("price cannot be negative");

    -3.0 နဲ့ Misprint က ဒီ line ကို ရောက်ပါတယ်။ main() ထဲက catch က "rejected Misprint: price cannot be negative" လို့ print ထုတ်ပြီး ဆက်သွားလို့ နောက်ဆုံး list မှာ book သုံးအုပ်ပဲ ရှိပါတယ်။

  3. Reference loop variablefor (int& n : nums) {

    int& n က vector ထဲက element တစ်ခုချင်းရဲ့ နောက်နာမည်ပါ၊ ဒါကြောင့် n *= 2 က vector ကိုယ်တိုင်ကို ပြောင်းပါတယ်။ doubleValues မှာ ဒီ & ရှိပြီး parameter မှာလည်း & ရှိလို့ ပြောင်းလဲမှုက caller အထိ ရောက်ပါတယ်။

  4. A parameter that copiesvoid doubleCopy(std::vector<int> nums) { // by value: only the copy changes

    ဒီမှာ loop က int& သုံးပေမယ့် nums ကိုယ်တိုင်က copy ပါ။ ပြောင်းလဲမှုက copy ထဲမှာပဲ ရှိပြီး function ပြီးတာနဲ့ ပျောက်သွားလို့ "after doubleCopy" line က 1 ကနေ 10 အတိုင်း ပြပါတယ်။

  5. Write through the pointer*ptr += 10; // change the int that ptr points to

    ptr က score ကို ညွှန်တာမို့ *ptr က score ရဲ့ နာမည်တစ်ခုလို အလုပ်လုပ်ပါတယ်။ ဒါကြောင့် *ptr = 100 နဲ့ score = 100 နှစ်ခုလုံး ထွက်ပါတယ်။

  6. A pointer that points nowhereint* nowhere = nullptr;

    nullptr က "ဘာကိုမှ မညွှန်ဘူး" လို့ ဆိုလိုပါတယ်။ ဒီ pointer ကို *nowhere လို့ dereference မလုပ်ရပါဘူး၊ ကိုယ်တိုင် if (nowhere == nullptr) နဲ့ အရင်စစ်ပါတယ်။

You should see
Task 1
  (no books)
  rejected Misprint: price cannot be negative
  C++ Basics       $8.50
  STL Guide       $12.00
  OOP in Depth    $15.75
Task 2
  ptr holds the address of score: true
  *ptr = 100, score = 100
  nowhere is null, so it must not be dereferenced
Task 3
  after doubleCopy: 1 2 3 4 5 6 7 8 9 10
  after doubleValues: 2 4 6 8 10 12 14 16 18 20
  negatives and zero: -6 0 8
  empty vector: (empty)

ဘာကြောင့် pointer ပြန်ပေးတာလဲ၊ reference မဟုတ်ဘဲ

Challenge ထဲက cheapest() ကို စဉ်းစားကြည့်ပါ။ Library အလွတ်မှာ "အဈေးအသက်သာဆုံး book" မရှိပါဘူး။ Reference က အမြဲ object တစ်ခုကို ညွှန်ရလို့ "ဘာမှမရှိ" ဆိုတာကို ဖော်ပြလို့ မရပါဘူး။ Pointer ကတော့ nullptr နဲ့ ပြောနိုင်ပါတယ်၊ ဒါမှမဟုတ် std::optional<Book> ကို ပြန်ပေးလို့လည်း ရပါတယ် (ဒါက copy ပြန်ပေးတာပါ)။

Pointer ပြန်ပေးရင် အဲဒီ pointer က vector ထဲက element တစ်ခုကို ညွှန်နေတာမို့ vector ကို ပြောင်းလိုက်တဲ့အခါ (push_back ကြောင့် reallocate ဖြစ်တာ ဒါမှမဟုတ် sort လုပ်တာ) မမှန်တော့နိုင်ပါတယ်။ Sort ပြီးရင် အဲဒီ element ရှိခဲ့တဲ့ နေရာမှာ တခြား book ရောက်နေနိုင်ပါတယ်။ ဒါကြောင့် ရလဒ်ကို ချက်ချင်းသုံးပါ၊ vector မပြောင်းခင်ပဲ ဖတ်ပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ

Inventory၊ စာကြည့်တိုက်၊ ဆိုင် app တွေမှာ ဒီ code ပုံစံကို နေ့တိုင်း တွေ့ရပါတယ်။ Domain class တစ်ခု (Book၊ Product) က ကိုယ့်စည်းကမ်းကို စောင့်ပြီး collection class က vector ကို ပိုင်ပါတယ်။ API တွေက read-only function တိုင်းမှာ const & ကို သုံးပြီး ပြောင်းရမယ့် function တွေမှာပဲ non-const & ကို သုံးလို့ code ကို ဖတ်တာနဲ့ "ဘယ် function က data ကို ပြောင်းနိုင်လဲ" ကို သိနိုင်ပါတယ်။

Pointer ကို ဒီ ခေတ်မှာ ပိုင်ဆိုင်မှု (ownership) မပါတဲ့ "ညွှန်ရုံ" အနေနဲ့ အသုံးများပါတယ်၊ C library တွေနဲ့ ချိတ်တဲ့အခါလည်း မလွဲမသွေ ကြုံပါတယ်။ ဈေးနှုန်းကို double နဲ့ ထားတာက exercise အတွက် လုံလောက်ပေမယ့် တကယ့် ငွေကြေး program မှာတော့ ပြဿနာ မဖြစ်အောင် ပြည့်ဂဏန်း (ဥပမာ ပြားအရေအတွက်) နဲ့ သိမ်းလေ့ရှိပါတယ်။ Sort လုပ်တဲ့အခါ ဈေးတူရင် title နဲ့ ဆက်စီတာကလည်း ပုံမှန်ပါပဲ၊ ဒါမှ screen တစ်ခုထဲမှာ run တိုင်း အစီအစဉ်တူတူ ထွက်ပါတယ်။

အမှားများ

ဖြစ်လေ့ရှိတဲ့ အမှားများ

ptr ကို ပြောင်းမိပြီး *ptr ကို မပြောင်းတာ

ptr = 100; က g++ ကနေ error: invalid conversion from 'int' to 'int*' [-fpermissive] ပေးပါတယ်။ ptr = ptr + 10; ကတော့ compile ဖြစ်ပါတယ်၊ ဒါပေမဲ့ int ဆယ်လုံး ဝေးတဲ့ နေရာကို ညွှန်စေပြီး score မပြောင်းပါဘူး၊ ဒီ pointer ကို ဖတ်ရင် undefined behaviour ပါ။ တန်ဖိုးကို ပြောင်းချင်ရင် *ptr += 10 လို့ ရေးပါ။

Range-for မှာ & မပါတာ

for (int n : nums) n *= 2; က element တစ်ခုချင်းရဲ့ copy ကို နှစ်ဆလုပ်ပြီး vector မပြောင်းပါဘူး။ g++ -Wall က warning: variable 'n' set but not used လို့ ပြတတ်လို့ warning ကို မကျော်ပါနဲ့။ Vector ကို ပြောင်းချင်ရင် int& n၊ ဖတ်ရုံသက်သက်ဆိုရင် const int& n ကို သုံးပါ။

Getter ကို const မလုပ်တာ

std::string getTitle() { ... } လို့ const မပါဘဲ ရေးပြီး const Book& b ကနေ b.getTitle() ကို ခေါ်ရင် g++ က error: passing 'const Book' as 'this' argument discards qualifiers [-fpermissive] လို့ ပြပါတယ်။ const Book& ကနေ ခေါ်လို့ရတာ const member function တွေပဲ ဖြစ်လို့ getter တိုင်းကို const မှတ်ပါ။

nullptr ကို စစ်မထားတာ

cheapest() လို function က library အလွတ်မှာ nullptr ပြန်ပါတယ်။ ရလဒ်ကို စစ်မထားဘဲ ->getTitle() လို့ ခေါ်ရင် undefined behaviour ဖြစ်ပါတယ်၊ Data ရှိတဲ့အချိန်မှာပဲ စမ်းနေရင် ဒီ bug က မပေါ်ဘဲ ပထမဆုံး user တစ်ယောက်က library အလွတ်ကို တကယ်ကြုံတဲ့အခါမှ ပေါ်လေ့ရှိပါတယ်။ Pointer ကို ခေါ်ပြီးတိုင်း if (p) သို့မဟုတ် if (p != nullptr) နဲ့ စစ်ပါ။

Mini challenge

Library class ကို ရေးပါ

Lesson ထဲက Book class ကို သုံးပြီး Library class တစ်ခု ရေးပါ။ Book တွေကို private vector ထဲ သိမ်းပြီး အဈေးအနည်းဆုံး book ကို pointer နဲ့ ပြန်ပေးတာ၊ စုစုပေါင်းတန်ဖိုး၊ အဈေးအလိုက်စီတာနဲ့ limit အောက်က book တွေကို ရွေးတာ လုပ်ပါ။ Library အလွတ်၊ အဈေးတူတဲ့ book နှစ်အုပ်နဲ့ ဘယ်တစ်အုပ်မှ မကိုက်တဲ့ filter ကို စမ်းပါ။

  • cheapest() က library အလွတ်မှာ nullptr၊ အဈေးတူရင် ပထမဆုံး ထည့်ထားတဲ့ book ကို ပြန်ပါ
  • totalValue() က library အလွတ်မှာ 0.0 ပြန်ပြီး std::accumulate ကို 0.0 နဲ့ စပါ (0 နဲ့ မစပါနဲ့)
  • sortByPrice() က အဈေးနည်းရာကစီပြီး တူရင် title အက္ခရာစဉ်နဲ့ ဆက်စီပါ
  • under(limit) က limit ထက် တင်းတင်းကျပ်ကျပ် နည်းတဲ့ book တွေကို copy အဖြစ် ပြန်ပါ
  • all() က const vector<Book>& ကို ပြန်ပါ၊ copy မကူးပါနဲ့
challenge.cpp
// Reuse the Book class (private title and price, checked constructor).

class Library {
public:
    void add(const Book& book);                   // TODO: store a copy
    const Book* cheapest() const;                 // TODO: nullptr when empty;
                                                  //       first of equal prices wins
    double totalValue() const;                    // TODO: 0.0 when empty
    void sortByPrice();                           // TODO: price ascending, then title
    std::vector<Book> under(double limit) const;  // TODO: price strictly below limit
    const std::vector<Book>& all() const;         // TODO: read-only view, no copy

private:
    std::vector<Book> books_;
};

int main() {
    // TODO: ask an empty library for cheapest() and totalValue()
    // TODO: add STL Guide 12.00, Pointers 101 8.50, C++ Basics 8.50, OOP in Depth 15.75
    // TODO: print the cheapest title and the total with 2 decimals
    // TODO: sort, then print all books, then under(12.0) and under(5.0)
}

ရလဒ်: Library အလွတ်မှာ "cheapest = none, total $0.00"၊ ပြီးရင် "Cheapest: Pointers 101"၊ "Total value: $44.75"၊ အဈေးအလိုက်စီထားတဲ့ book လေးအုပ် (C++ Basics ကို Pointers 101 ရှေ့မှာ ထားရမယ်)၊ "Under $12.00 (2)" နဲ့ "Under $5.00 (0)" တို့ ထွက်ရပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

cheapest() အတွက် std::min_element နဲ့ comparator ကို သုံးပြီး return &*it လို့ ရေးပါ။ min_element က တူတဲ့ အနည်းဆုံးတွေထဲက ပထမဆုံးကို ပြန်ပေးပါတယ်။ std::accumulate(begin, end, 0.0, lambda) မှာ 0.0 အစား 0 ကို ရေးရင် sum ကို int အဖြစ် သိမ်းလို့ ဒဿမတွေ ပျောက်ပါတယ်၊ ဥပမာ 44.75 က 43 ဖြစ်သွားပါတယ်။ under() အတွက် std::copy_if နဲ့ std::back_inserter သုံးနိုင်ပါတယ်။

အဖြေ ကြည့်ရန်
challenge.cpp
#include <algorithm>
#include <format>
#include <iostream>
#include <iterator>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

class Book {
public:
    Book(std::string title, double price) : title_(std::move(title)), price_(price) {
        if (price_ < 0.0) {
            throw std::invalid_argument("price cannot be negative");
        }
    }

    const std::string& getTitle() const { return title_; }
    double getPrice() const { return price_; }

private:
    std::string title_;
    double price_;
};

class Library {
public:
    void add(const Book& book) { books_.push_back(book); }

    // nullptr when the library is empty; on a tie the book added first wins.
    const Book* cheapest() const {
        if (books_.empty()) {
            return nullptr;
        }
        auto it = std::min_element(books_.begin(), books_.end(),
                                   [](const Book& a, const Book& b) {
                                       return a.getPrice() < b.getPrice();
                                   });
        return &*it;
    }

    double totalValue() const {
        // 0.0, not 0: the start value decides the type of the running sum
        return std::accumulate(books_.begin(), books_.end(), 0.0,
                               [](double sum, const Book& b) {
                                   return sum + b.getPrice();
                               });
    }

    void sortByPrice() {
        std::sort(books_.begin(), books_.end(), [](const Book& a, const Book& b) {
            if (a.getPrice() != b.getPrice()) {
                return a.getPrice() < b.getPrice();
            }
            return a.getTitle() < b.getTitle();  // same price: alphabetical
        });
    }

    std::vector<Book> under(double limit) const {
        std::vector<Book> result;
        std::copy_if(books_.begin(), books_.end(), std::back_inserter(result),
                     [limit](const Book& b) { return b.getPrice() < limit; });
        return result;
    }

    const std::vector<Book>& all() const { return books_; }

private:
    std::vector<Book> books_;
};

void printBooks(const std::string& label, const std::vector<Book>& books) {
    std::cout << label << " (" << books.size() << ")\n";
    for (const Book& b : books) {
        std::cout << std::format("  {:<14}{:>8}\n", b.getTitle(),
                                 std::format("${:.2f}", b.getPrice()));
    }
}

int main() {
    Library library;
    const Book* first = library.cheapest();
    std::cout << "Empty library: cheapest = " << (first ? first->getTitle() : "none")
              << std::format(", total ${:.2f}\n", library.totalValue());

    library.add(Book("STL Guide", 12.0));
    library.add(Book("Pointers 101", 8.5));
    library.add(Book("C++ Basics", 8.5));
    library.add(Book("OOP in Depth", 15.75));

    const Book* cheap = library.cheapest();
    std::cout << "Cheapest: " << cheap->getTitle() << '\n';
    std::cout << std::format("Total value: ${:.2f}\n", library.totalValue());

    library.sortByPrice();
    printBooks("Sorted by price", library.all());
    printBooks("Under $12.00", library.under(12.0));
    printBooks("Under $5.00", library.under(5.0));
}

Quick Quiz 1 / 3

int score = 90; int* p = &score; *p += 10; ပြီးနောက် ဘာမှန်လဲ။

Quick Quiz 2 / 3

void f(std::vector<int> v) { for (int& x : v) x *= 2; } ကို nums = {1, 2, 3} နဲ့ ခေါ်ပြီးနောက် caller ရဲ့ nums က ဘာလဲ။

Quick Quiz 3 / 3

[STL Guide 12.00၊ Pointers 101 8.50၊ C++ Basics 8.50၊ OOP in Depth 15.75] ရှိတဲ့ library မှာ std::min_element နဲ့ cheapest() က ဘယ် title ကို ညွှန်မလဲ။

မှတ်ထားရမယ့် အချက်များ

  • & နဲ့ * က နေရာကို လိုက်ပြီး အဓိပ္ပာယ်ကွဲပါတယ်: type ထဲက & က နာမည်၊ expression ထဲက & က address၊ *p က ညွှန်ရာ object
  • Function parameter ကို value နဲ့ ယူရင် copy ကိုပဲ ပြောင်းပြီး caller မပြောင်းပါဘူး၊ Range-for မှာလည်း & ပါမှ element ကို ပြောင်းလို့ရပါတယ်
  • Pointer ကို dereference မလုပ်ခင် nullptr ကို စစ်ပြီး vector ပြောင်းတဲ့အခါ အရင်က pointer ကို မယုံပါနဲ့
  • Constructor မှာ rule ကို စစ်ထားရင် vector ထဲ မှားတဲ့ object မဝင်နိုင်ပါဘူး

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Exercises: OOP & STL Challenge | Thuta Learning