Let's Think About This For a Second
In Part 1, we finished the Student class and the menu skeleton. In Part 2, we'll implement the actual features — adding a new student, displaying the whole student list, and searching for a student by roll number. We'll pass functions the vector<Student>& as a reference parameter, so the vector can be modified directly without copying — a practical way to put the reference topic to use. We'll also use loops and string comparison for the search feature.
Let's Build It
Build the addStudent(vector<Student>& students) function to read name, roll, and marks from the user with cin, then add them to the vector with push_back(). In displayAll(const vector<Student>& students), use a range-based for loop to print each student's name, roll, and marks. In searchByRoll(const vector<Student>& students, int roll), loop through to find the student with the matching roll number — show the details if found, or "Not found" if not. Wire up cases 1 and 2 in main()'s switch statement to call these functions, and add case 4 for Search By Roll as a new menu item.
Example 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; }Choosing Add Student from the menu and entering data shows "Student added!", and choosing Display All shows the full student list in roll - name - marks format.5-Minute Try It
Using searchByRoll() as a model, write your own searchByName(const vector<Student>& students, string name) function — just compare the name string with the == operator.
A Quick Word of Caution
If you don't mark a vector parameter with & (reference), it gets copied on every call and can slow things down. For functions that don't modify the data, use const vector<Student>& instead.