ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ set က warm-up ထက် ပိုခက်ပြီး, Advanced chapter က class/object/constructor/access-specifier နဲ့ Intermediate chapter က pointer/reference/STL vector topic တွေကို ပေါင်းစပ်စမ်းသပ်ပါမယ်။ Task တွေက production code လိုမျိုး class design ဆွဲရတာ, pointer နဲ့ memory address ကို တိုက်ရိုက်ကိုင်တွယ်ရတာ ပါဝင်ပါတယ်။ ကိုယ်တိုင်ကြိုးစားရေးပြီးမှသာ solution ကို ကြည့်ပါ - ဒီအဆင့်မှာ error handling logic ကိုပါ ထည့်တွေးနိုင်ရင် ပိုကောင်းပါတယ်။
လေ့ကျင့်ခန်းများ
Task 1: Book class တစ်ခုကို title (string), price (double) private member နဲ့ constructor, getter method တွေနဲ့ ဖန်တီးပါ - ပြီးရင် vector<Book> ထဲကို Book object 3 ခု ထည့်ပြီး loop နဲ့ display လုပ်ပါ။ Task 2: int variable တစ်ခု ဖန်တီးပြီး pointer နဲ့ address ကို print ထုတ်ကြည့်ပါ - ပြီးရင် dereference (*) သုံးပြီး pointer ကနေ value ကို 10 တိုး update လုပ်ပါ၊ original variable ရဲ့ value ပြောင်းသွားခြင်း ရှိမရှိ confirm လုပ်ပါ။ Task 3: vector<int> တစ်ခုထဲ integer 10 ခု ထည့်ပြီး, reference parameter (vector<int>&) ယူတဲ့ function တစ်ခုနဲ့ vector ထဲက value အားလုံးကို 2 ဆ တိုးပြီး, function ကနေ ပြန်လာချိန် original vector ပြောင်းသွားခြင်း ရှိမရှိ စစ်ကြည့်ပါ။
Code နမူနာ
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Book {
private:
string title;
double price;
public:
Book(string t, double p) : title(t), price(p) {}
string getTitle() const { return title; }
double getPrice() const { return price; }
};
void doubleValues(vector<int>& nums) {
for (int& n : nums) {
n = n * 2;
}
}
int main() {
// Task 1
vector<Book> 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));
for (const Book& b : books) {
cout << b.getTitle() << " - $" << b.getPrice() << "\n";
}
// Task 2
int score = 90;
int* ptr = &score;
cout << "Address: " << ptr << ", Value: " << *ptr << "\n";
*ptr += 10;
cout << "Updated score: " << score << "\n";
// Task 3
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
doubleValues(nums);
for (int n : nums) cout << n << " ";
cout << "\n";
return 0;
}Task 2 run ပြီးရင် score ရဲ့ original value 90 ဟာ pointer dereference ကြောင့် 100 ဖြစ်သွားတာ confirm ဖြစ်ပြီး, Task 3 run ရင် nums vector ထဲက value အားလုံး 2 ဆတိုးထားတာ တွေ့ရမှာပါ။၅ မိနစ် စမ်းကြည့်
Task 1 ရဲ့ Book class ထဲကို sortByPrice(vector<Book>& books) function တစ်ခု ထပ်ရေးကြည့်ပါ - std::sort() နဲ့ lambda comparator ကို Student Manager project က idea ယူပြီး apply လုပ်ကြည့်ပါ။
သတိလေးတစ်ချက်
Pointer arithmetic (ptr + 10) နဲ့ dereference (*ptr += 10) ကို မရောမှားပါနဲ့ - pointer ကို ကိုယ်တိုင် ပြောင်းလိုက်ရင် address ပဲပြောင်းပြီး, value ကို ပြောင်းချင်ရင် * (dereference) ကို အမြဲသုံးရပါမယ်။