C++ Lesson 48 – STL Mini Project | Dataplexa
STL · Lesson 48

STL Mini Project

You have met the containers — vector, list, set, map, queue — and the algorithms — sort, find, count, transform. Now it is time to put them together. In this lesson you will build a complete Student Records Manager: a small program that stores a class of students, shows the class list, ranks them by marks, searches by roll number, lists the toppers, and works out the class average. Every feature uses one STL tool, and none of them needs a hand-written loop.

1. What We Are Building

Our program keeps one class of four students. Each student has a name, a roll number and a marks total. The manager must do six jobs: store the students, show the class list, rank them by marks, find one student by roll number, list the toppers, and report the passes and the class average. Here is the plan — one tool for each job:

Feature Tool used Why this one
Store the studentsvector<Student>Grows as students join, keeps order, easy to sort
Show the class listRange-based for loopReads every student, one line per student
Find a roll numberfind_if + lambdaSearches by any condition you write
Rank by markssort + lambdaOne line, fast, no hand-written swaps
List the topperscopy_if + back_inserterCopies only the matches into a new list
Class averageaccumulateAdds everything without a loop

We will build the program one step at a time, and each step is a small program you can run on its own. At the end, Step 8 joins all the pieces into the complete manager.

2. Step 1: The Student and the List

Every student is one small bundle of three facts: a name (a string), a roll number (an int) and marks (an int). A struct holds those three facts together as one value, and a vector<Student> holds all the students. Adding a student is one push_back call.

Code story: we define a Student struct with a name, a roll number and marks. Then we create an empty vector called classList and add four students with push_back — Asha, Ravi, Maya and Arjun. Finally we print the size of the list to prove the four students are in. Watch the braces in push_back: {"Asha", 101, 88} builds one Student in a single line.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

int main() {
    vector<Student> classList;

    classList.push_back({"Asha", 101, 88});
    classList.push_back({"Ravi", 102, 74});
    classList.push_back({"Maya", 103, 95});
    classList.push_back({"Arjun", 104, 61});

    cout << "Students in class: " << classList.size() << endl;
    return 0;
}
Students in class: 4
What just happened?

The struct groups three different types into one Student value, and the vector stores four of them in order. push_back copies each braced value into the list, and size() confirms there are 4 students. From now on, every step of the project works on this same classList.

3. Step 2: Showing the Class List

A list nobody can see is not useful, so the first real feature is a display function. It takes the vector by const reference — const vector<Student>& — so it reads the students without copying the whole list and without changing anything. A range-based for loop prints one line per student.

Code story: we write a small function called showAll that walks through the vector and prints each student’s roll, name and marks. In main we build the same four students — this time all at once with an initializer list — and call showAll. Watch the & in the parameter: it means “use the real list, not a copy”.

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

void showAll(const vector<Student>& students) {
    for (const Student& s : students)
        cout << s.roll << "  " << s.name << "  " << s.marks << endl;
}

int main() {
    vector<Student> classList = {
        {"Asha", 101, 88},
        {"Ravi", 102, 74},
        {"Maya", 103, 95},
        {"Arjun", 104, 61}
    };

    cout << "Class list:" << endl;
    showAll(classList);
    return 0;
}
Class list:
101  Asha  88
102  Ravi  74
103  Maya  95
104  Arjun  61
What just happened?

The loop reads each Student and prints its three fields. The students appear in the order they were added — 101, 102, 103, 104 — because a vector keeps insertion order. And because showAll takes a const reference, printing the list costs nothing extra: no copy of the four students is made.

4. Step 3: Ranking by Marks

Who came first in the class? That is a sort. The default sort does not know how to compare two Students, so we give it a lambda that says “put the bigger marks first”. One call, and the vector is in rank order — highest marks first.

Code story: we sort classList with a lambda that compares a.marks > b.marks, so the highest marks come first. Then we print the names and marks in the new order. Watch the lambda: the > sign is what makes the order “best first” — a < sign would put the lowest marks first.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

int main() {
    vector<Student> classList = {
        {"Asha", 101, 88},
        {"Ravi", 102, 74},
        {"Maya", 103, 95},
        {"Arjun", 104, 61}
    };

    sort(classList.begin(), classList.end(),
         [](const Student& a, const Student& b) {
             return a.marks > b.marks;
         });

    cout << "Ranked by marks:" << endl;
    for (const Student& s : classList)
        cout << s.name << "  " << s.marks << endl;
    return 0;
}
Ranked by marks:
Maya  95
Asha  88
Ravi  74
Arjun  61
What just happened?

sort rearranged the vector in place: Maya (95) moved to the front, then Asha (88), Ravi (74) and Arjun (61). The lambda only compares marks — the names and roll numbers travel with their student, so no data is ever mixed up. The topper is now simply the first element of the vector.

5. Step 4: Searching by Roll Number

A teacher usually looks a student up by roll number, not by position in the list. That is a job for find_if: give it a lambda that tests one condition — “this student’s roll equals the one I want” — and it returns an iterator to the first match, or end() when nobody matches.

Code story: we search for roll 103. The lambda captures the wanted number and tests s.roll == wanted for each student. When the match is found, we print the student’s name and marks using the iterator. Then we search for roll 999, which does not exist, to see the “not found” case. Watch the two checks against classList.end() — that is the only safe “did we find it?” test.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

int main() {
    vector<Student> classList = {
        {"Asha", 101, 88},
        {"Ravi", 102, 74},
        {"Maya", 103, 95},
        {"Arjun", 104, 61}
    };

    int wanted = 103;
    auto it = find_if(classList.begin(), classList.end(),
                      [wanted](const Student& s) {
                          return s.roll == wanted;
                      });

    if (it != classList.end())
        cout << "Found: " << it->name
             << " scored " << it->marks << endl;
    else
        cout << "Roll " << wanted << " not found" << endl;

    int absent = 999;
    auto gone = find_if(classList.begin(), classList.end(),
                        [absent](const Student& s) {
                            return s.roll == absent;
                        });
    cout << "Roll 999 present? " << (gone != classList.end()) << endl;
    return 0;
}
Found: Maya scored 95
Roll 999 present? 0
What just happened?

find_if stopped at Maya, whose roll is 103, and the iterator let us read her name and marks with it->name and it->marks. The search for 999 reached the end, so (gone != classList.end()) printed 0 — false. Notice we used find_if, not find: find compares whole Student objects, and cannot search by one field.

6. Step 5: Filtering the Toppers

A “toppers list” is the class list with a filter on it: keep only the students whose marks are 85 or above. copy_if does exactly that — it copies only the elements that pass a test into a new container. The new list is built with back_inserter, a small helper that appends each copied student to the end of the new vector.

Code story: we create an empty vector called toppers. copy_if walks through classList and copies only the students with marks >= 85 into it, using back_inserter to grow the new list one student at a time. Then we print the toppers. Watch that the original classList is untouched — copy_if never changes its input.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

int main() {
    vector<Student> classList = {
        {"Asha", 101, 88},
        {"Ravi", 102, 74},
        {"Maya", 103, 95},
        {"Arjun", 104, 61}
    };

    vector<Student> toppers;
    copy_if(classList.begin(), classList.end(),
            back_inserter(toppers),
            [](const Student& s) { return s.marks >= 85; });

    cout << "Toppers (85 and above):" << endl;
    for (const Student& s : toppers)
        cout << s.name << "  " << s.marks << endl;
    return 0;
}
Toppers (85 and above):
Asha  88
Maya  95
What just happened?

Only Asha (88) and Maya (95) passed the test, so the new vector holds exactly two students. Ravi (74) and Arjun (61) were left behind — and the original classList still holds all four. copy_if is the standard “make a filtered copy” tool: change the lambda, and you get a different list — students below 75, students above 90, anyone you like.

7. Step 6: Passes and Averages

The last two statistics are counting and adding. count_if counts how many students pass (marks 40 or above). accumulate adds up all the marks — but because each element is a Student, not a plain number, its lambda takes the running total and a student and returns total + s.marks. Dividing by the class size gives the average.

Code story: we ask count_if how many students scored 40 or more. Then accumulate adds the four marks: 88 + 74 + 95 + 61. Finally we divide the total by classList.size() using a double, so the average keeps its decimal part. Watch the (double) cast — without it, 318 / 4 would be integer division and the answer would come out as 79 instead of 79.5.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

int main() {
    vector<Student> classList = {
        {"Asha", 101, 88},
        {"Ravi", 102, 74},
        {"Maya", 103, 95},
        {"Arjun", 104, 61}
    };

    int passed = count_if(classList.begin(), classList.end(),
                          [](const Student& s) {
                              return s.marks >= 40;
                          });
    int total = accumulate(classList.begin(), classList.end(), 0,
                           [](int sum, const Student& s) {
                               return sum + s.marks;
                           });
    double average = (double)total / classList.size();

    cout << "Passed: " << passed << " of " << classList.size() << endl;
    cout << "Total marks: " << total << endl;
    cout << "Class average: " << average << endl;
    return 0;
}
Passed: 4 of 4
Total marks: 318
Class average: 79.5
What just happened?

All four students scored 40 or above, so count_if reported 4 of 4 passes. accumulate added the marks to 318, and 318 divided by 4 gave 79.5. Two one-line algorithms replaced two hand-written loops — and the only line that needed a little thought was the lambda that pulls s.marks out of each Student.

8. The Complete Program

Now join all six steps into one program. It builds the class, shows the list, sorts it, reads the topper straight from the front of the sorted vector, filters the toppers, and finishes with the class average. Read it top to bottom: every feature you built separately is here, unchanged, in the same order.

Code story: this is the whole manager in one file. main builds the four students, prints the class list with showAll, sorts by marks and reads the topper from classList.front(), filters the toppers with copy_if, and adds up the marks with accumulate. Watch how short it is — the entire program is one struct, one small function and about twenty lines in main.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;

struct Student {
    string name;
    int roll;
    int marks;
};

void showAll(const vector<Student>& students) {
    for (const Student& s : students)
        cout << s.roll << "  " << s.name << "  " << s.marks << endl;
}

int main() {
    vector<Student> classList = {
        {"Asha", 101, 88},
        {"Ravi", 102, 74},
        {"Maya", 103, 95},
        {"Arjun", 104, 61}
    };

    cout << "Class list:" << endl;
    showAll(classList);

    sort(classList.begin(), classList.end(),
         [](const Student& a, const Student& b) {
             return a.marks > b.marks;
         });
    cout << "Topper: " << classList.front().name
         << " (" << classList.front().marks << ")" << endl;

    vector<Student> toppers;
    copy_if(classList.begin(), classList.end(),
            back_inserter(toppers),
            [](const Student& s) { return s.marks >= 85; });
    cout << "Toppers: " << toppers.size() << endl;

    int total = accumulate(classList.begin(), classList.end(), 0,
                           [](int sum, const Student& s) {
                               return sum + s.marks;
                           });
    cout << "Class average: "
         << (double)total / classList.size() << endl;
    return 0;
}
Class list:
101  Asha  88
102  Ravi  74
103  Maya  95
104  Arjun  61
Topper: Maya (95)
Toppers: 2
Class average: 79.5
What just happened?

The program prints the class in its original order, then sorts and reports Maya as topper with 95. copy_if finds two toppers, and accumulate reports the average 79.5. Notice what is missing: there is not one hand-written loop that searches, sorts or adds — the STL does all of it.

Compare each job with the way you would have written it before this level:

Task Hand-written loop STL way
Sorting 4 studentsA nested loop with swapssort(v.begin(), v.end(), cmp)
Finding roll 103A loop with an if and a flagfind_if(v.begin(), v.end(), test)
Counting the passesA counter variable and an ifcount_if(v.begin(), v.end(), test)
Adding up the marksA sum variable and a loopaccumulate with a lambda that adds s.marks

9. Common Mistakes

Projects are where small mistakes meet real data. Here are the five that catch beginners most often in this kind of program:

Mistake What happens Fix
Passing the vector by value to a functionThe function works on a copy — changes disappearPass by reference: vector<Student>&
Forgetting to sort before binary_searchbinary_search gives a wrong answer on unsorted dataSort first, then search
Using find instead of find_if for studentsfind compares whole Student objects and will not match a roll numberUse find_if with a lambda on roll
Storing students in a map keyed by nameTwo students with the same name overwrite each otherKey by roll number, which is unique
Forgetting the (double) cast in the averageInteger division drops the decimal — 79 instead of 79.5Write (double)total / size

Practice — Try It Yourself

Open your editor and extend the project. Each task adds one real feature to the manager you just built.

  1. Add a fifth student {"Neha", 105, 91} and print the class list again — check that she appears in the toppers.
  2. Write a function that searches by name instead of roll number, using find_if on s.name.
  3. Use count_if to count how many students scored below 75 — print “Need help: X”.
  4. Extend the program: store the students in a map<int, Student> keyed by roll number, then look up roll 102 with map::find.

Which container is the natural home for a list of students you need to sort?


What does copy_if do?


Why do the project functions take vector<Student>& instead of vector<Student>?


Fill in the blanks — type the missing word into the box.

To sort the students by marks you call with a lambda that compares marks.


The function copies only the students who pass a test into a new vector.


Store the students in a so the list can grow and be sorted easily.


UP NEXT

Lesson 49 — Modern C++ Overview

Next, a new level begins: Modern C++. See what changed in C++11 and later — and why the modern way of writing C++ is shorter, safer and easier to read.