Summary - Structs
- C++ course
- Beginner
- Lesson 99/116
- 5 min
Combine struct and vector to write a student database.
Summary: Student database
In this summary we will combine struct, function and vector to build a small student database. Each student is represented by a Student struct; all students are kept in a vector<Student>.
The plan: first define the Student struct, then write the addStudent and printAll functions. addStudent creates a new student and adds it to the vector; printAll prints every student with a loop. This brings together the important struct tools of the beginner level in one place.
Practice Student struct and printing
Define struct Student { string name; int grade; };. Create vector<Student> students;. Build a Student s;, assign s.name = "Ayşe"; and s.grade = 90;, then add it with students.push_back(s);. Use a range for to print each student's name and grade with cout << st.name << " - " << st.grade << endl;.
Starter code
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Define the Student struct
int main() {
// declare a Student vector, add a student, print with for
return 0;
}Sample solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int grade;
};
int main() {
vector<Student> students;
Student s;
s.name = "Ayşe";
s.grade = 90;
students.push_back(s);
for (Student st : students) {
cout << st.name << " - " << st.grade << endl;
}
return 0;
}Expected output
Ayşe - 90
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each tool with its job
| Term | Meaning |
|---|---|
struct Student |
student type |
vector<Student> |
student list |
addStudent |
adds a new student |
2 What does students.size() return for vector<Student> students;?
- the first element
- the last element
- adds a new element
- the length Correct answer
Explanation: size() returns the number of elements in the vector.
3 Fill in the blank: push_back call
Student s;
s.name = "Ali";
students.____(s);
Student s;
s.name = "Ali";
students.push_back(s);
Explanation: push_back adds a new element to a vector.