ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
Part 1 မှာ Student class နဲ့ menu skeleton ပြီးသွားပါပြီ။ Part 2 မှာတော့ actual feature တွေကို implement လုပ်ပါမယ် - student အသစ်ထည့်ခြင်း, student list အားလုံးကို display လုပ်ခြင်း, roll number နဲ့ student ရှာဖွေခြင်း စတာတွေပါ။ function တွေကို vector<Student>& ဆိုပြီး reference by parameter ပေးပို့ပြီး, vector ကို copy မလုပ်ဘဲ direct modify လုပ်နိုင်အောင် စီစဉ်ပါမယ် - ဒါက reference topic ကို practical ဖြစ်အောင် အသုံးချတာဖြစ်ပါတယ်။ loop နဲ့ string comparison ကို search feature မှာ အသုံးပြုပါမယ်။
လက်တွေ့ ဆောက်ကြည့်မယ်
addStudent(vector<Student>& students) function ကို ဖန်တီးပြီး user ဆီက name, roll, marks ကို cin နဲ့ဖတ်ပြီး vector ထဲကို push_back() နဲ့ ထည့်ပါ။ displayAll(const vector<Student>& students) function မှာ range-based for loop နဲ့ student တစ်ယောက်ချင်းစီရဲ့ name, roll, marks ကို print ထုတ်ပါ။ searchByRoll(const vector<Student>& students, int roll) function မှာ loop သုံးပြီး roll number တူတဲ့ student ကို ရှာပြီး, ရှိရင် detail ပြ, မရှိရင် "Not found" ပြပါ။ main() ရဲ့ switch statement ထဲမှာ case 1, 2 တွေကို ဒီ function တွေခေါ်အောင် ချိတ်ဆက်ပြီး, case 4 အနေနဲ့ Search By Roll ကို menu ထဲထပ်ထည့်ပါ။
Code နမူနာ
void addStudent(vector<Student>& students) {
string name;
int roll;
double marks;
cout << "Enter name: ";
cin >> name;
cout << "Enter roll: ";
cin >> roll;
cout << "Enter marks: ";
cin >> marks;
students.push_back(Student(name, roll, marks));
cout << "Student added!\n";
}
void displayAll(const vector<Student>& students) {
if (students.empty()) {
cout << "No students yet.\n";
return;
}
for (const Student& s : students) {
cout << s.getRoll() << " - " << s.getName()
<< " - Marks: " << s.getMarks() << "\n";
}
}
void searchByRoll(const vector<Student>& students, int roll) {
for (const Student& s : students) {
if (s.getRoll() == roll) {
cout << "Found: " << s.getName()
<< " - Marks: " << s.getMarks() << "\n";
return;
}
}
cout << "Student not found.\n";
}
// main() ရဲ့ switch ထဲမှာ:
// case 1: addStudent(students); break;
// case 2: displayAll(students); break;
// case 4: { int r; cin >> r; searchByRoll(students, r); break; }Menu ကနေ Add Student ရွေးပြီး data ထည့်ပြီးရင် "Student added!" ပြပြီး, Display All ရွေးရင် student list အားလုံးကို roll - name - marks format နဲ့ ပြပါမယ်။၅ မိနစ် စမ်းကြည့်
searchByRoll() ကို model ယူပြီး searchByName(const vector<Student>& students, string name) function တစ်ခု ကိုယ်တိုင်ရေးကြည့်ပါ - name string ကို == operator နဲ့ compare လုပ်ရုံပါပဲ။
သတိလေးတစ်ချက်
Function parameter မှာ vector ကို & (reference) မထားရင် call တိုင်း copy ဖြစ်ပြီး slow ဖြစ်နိုင်ပါတယ်။ modify မလုပ်တဲ့ function တွေမှာတော့ const vector<Student>& အသုံးပြုပါ။