TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 5 of 18 · Free

STL in C++ – vector, map, set and Algorithms

⏱ About 40 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Store a growing list in a vector and loop over it
  • Sort, search and count with STL algorithms
  • Count and look up things with map, and keep unique values with set

In Lesson 1 you stored 5 marks in a fixed array. But what if 37 students join today and 3 more next week? And how do you count how many times each tiffin dish was ordered? The Standard Template Library (STL) gives you ready-made, tested tools for exactly this.

What is the STL in C++ and how do I use vector?

The STL is a part of the C++ standard library. It has containers (boxes that hold many values) and algorithms (ready functions like sort).

vector is a list that can grow. vector<int> means "a vector of ints". push_back adds a value at the end. size() tells how many values it holds.

for (int m : marks) is a range-based for loop. It visits every value in order, so you can't go past the end by mistake.

(double)total turns total into a double for this one division, so the average keeps its decimal part.

Try it: push_back two more marks and run again. The average updates by itself.

🧩 C++ — you can edit this code
Output
Students: 5
First: 72, last: 54
Average: 74

💡 marks[i] does not check the index. Reading past the end is undefined behaviour, so always keep i below marks.size().

How do I sort and search a vector in C++?

The header <algorithm> gives ready functions. sort(v.begin(), v.end()) sorts from smallest to biggest. begin() and end() mark the start and the end of the range.

Add greater<int>() to sort from biggest to smallest. count counts a value. find looks for a value and returns end() if it is not there.

max_element gives a position, not a value, so put * in front to read the value.

Try it: search for 100 instead of 47 and run again.

🧩 C++ — you can edit this code
Output
Smallest first: 0 5 12 12 34 47 88 
Top score: 88
Scores of 12: 2
Highest (max_element): 88
Someone scored 47

How does map work in C++?

A map stores pairs: a key and its value. map<string, int> maps a name to a number, like a dish name to the number of orders.

orders[dish]++ adds one to that dish. If the dish is not in the map yet, [] first creates it with value 0. That makes counting very short.

A map keeps its keys sorted, so the loop prints dishes in alphabetical order. Each item p has p.first (the key) and p.second (the value).

Try it: add "vada" twice to the list and run again.

🧩 C++ — you can edit this code
Output
dosa: 3
idli: 2
poha: 1
No upma today

💡 auto asks the compiler to work out the type for you. Here it is pair<const string, int>.

What is a set in C++ and when should I use it?

A set keeps unique values in sorted order. If you insert a value that is already there, nothing happens.

Use it when you only care whether something is present, not how many times. For example, which students borrowed a library book this week.

count(x) returns 1 if x is in the set, else 0.

Try it: insert "Zoya" and "Arjun" again and check that size() does not change.

🧩 C++ — you can edit this code
Output
3 different students borrowed books:
- Arjun
- Neha
- Zoya
Did Kabir borrow? no

How do I sort a vector of structs in C++ with a lambda?

A struct is a class whose members are public by default (Lesson 2). Often you want to sort such objects by one field, like batters by runs. Give sort a third argument: a rule that says which of two items comes first.

[](const Batter& a, const Batter& b) { return a.runs > b.runs; } is a lambda: a small function written right where you need it. It returns true when a should come before b.

stable_sort keeps tied items in their old order, so two batters on the same score stay as they were.

Try it: change > to < to put the lowest score first. Then sort by name instead.

🧩 C++ — you can edit this code
Output
Dev 78
Rahul 45
Om 45
Sanju 12

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

vector<int> v = {4, 8};
v.push_back(15);
v.push_back(16);
v.pop_back();
cout << v.size() << " " << v.back() << "\n";

Question 2. What does this print?

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<int> s = {3, 1, 3, 2, 1};
    cout << s.size() << *s.begin() << "\n";
    return 0;
}

Question 3. What does this print?

map<string, int> stock;
stock["pen"] = 10;
if (stock["pencil"] == 0) {
    cout << "no pencils, ";
}
cout << stock.size() << "\n";

🧩 Your challenge

The canteen writes down every tiffin order. Read the number of orders, then the dish names. Count each dish with a map and print the counts in alphabetical order, then the most ordered dish. For 8 orders "dosa idli dosa poha idli dosa upma poha" print: dosa: 3 idli: 2 poha: 2 upma: 1 Most ordered: dosa

Expected output (with the inputs given):
How many orders? 8
Dishes: dosa idli dosa poha idli dosa upma poha
dosa: 3
idli: 2
poha: 2
upma: 1
Most ordered: dosa
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

vector<int> marks = {40, 50};
for (int m : marks) {
    m = m + 5;
}
cout << marks[0] << " " << marks[1] << "\n";

Compiles and runs, but prints: 40 50 ⏎

✅ Right

vector<int> marks = {40, 50};
for (int& m : marks) {
    m = m + 5;
}
cout << marks[0] << " " << marks[1] << "\n";

int m gets a copy of each value, so the vector does not change. Use int& m to change the real values, just like references in Lesson 1.

❌ Wrong

vector<int> v = {1, 2, 3};
cout << v << "\n";

Line 2: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'vector<int>')

✅ Right

vector<int> v = {1, 2, 3};
for (int x : v) cout << x << " ";
cout << "\n";

cout does not know how to print a whole vector. Loop over it and print each value.

❌ Wrong

map<string, int> stock = {{"pen", 10}};
if (stock["eraser"] > 0) cout << "have erasers\n";
cout << "items: " << stock.size() << "\n";

Compiles and runs, but prints: items: 2 ⏎

✅ Right

map<string, int> stock = {{"pen", 10}};
if (stock.count("eraser") && stock["eraser"] > 0) cout << "have erasers\n";
cout << "items: " << stock.size() << "\n";

[] quietly adds a missing key with value 0. Check with count() (or find()) first when you only want to look.

📌 Remember

  • vector is a list that grows: push_back, size(), back(), and range-for loops.
  • <algorithm> gives sort, find, count and max_element; they work on begin()..end().
  • map stores key → value pairs, sorted by key; [] creates missing keys.
  • set keeps unique values in sorted order.
  • A lambda passed to sort decides the order of your own structs.

Finished the quiz and the challenge?

Questions students ask

What is the difference between an array and a vector in C++?

An array has a fixed size chosen when you write the code. A vector can grow and shrink while the program runs, knows its own size and can be copied or returned like a normal value. In modern C++, prefer vector.

What is the difference between map and unordered_map?

map keeps keys sorted. unordered_map keeps them in no fixed order but is usually faster for big data. Use map when you need sorted output, like in this lesson.

Why is it called the Standard Template Library?

Its containers and algorithms are templates: they are written once and work for any type, like vector<int> or vector<string>. Lesson 9 shows how to write your own templates.

Is the STL allowed in programming contests?

Yes. The STL is part of standard C++, so contests that accept C++ accept it. Contest coders use vector, sort and map all the time.