Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 53

Introduction to STL in C++

In this lesson: Introduction to the C++ Standard Template Library — containers, iterators, algorithms — beginner guide with code. In Hindi & English.

What is the STL?

Suppose you need to store marks of any number of students, sort them, and find the highest. In C you would write your own dynamic array, your own sort and your own search — and debug all three. The Standard Template Library (STL) gives you all of this ready-made, tested and fast:

C++
std::vector<int> marks = {78, 91, 66, 84};
std::sort(marks.begin(), marks.end());

The STL is a collection of templates — generic code that works with any data type — for data structures and algorithms. It was designed by Alexander Stepanov and became part of standard C++ in 1998. This lesson is a first overview; for a deeper tour see the C++ STL guide.

The four components

ComponentWhat it doesExamples
ContainersStore a collection of objectsvector, list, deque, set, map, unordered_map
IteratorsPoint to elements and move through a containerbegin(), end(), ++it, *it
AlgorithmsProcess ranges of elementssort, find, count, reverse, max_element
Function objects / lambdasCustomise how algorithms behavestd::greater<int>(), [](int a, int b){ return a > b; }

The key design idea: algorithms don't know about containers. They work on a pair of iterators (a range), so one sort works on a vector, a deque or a plain array.

First example: store, sort, search

C++
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> marks = {78, 91, 66, 84, 91, 55};

    marks.push_back(73);                                   // container grows

    std::sort(marks.begin(), marks.end());                 // algorithm
    std::cout << "Sorted: ";
    for (int m : marks) std::cout << m << " ";
    std::cout << "\n";

    auto best = std::max_element(marks.begin(), marks.end());   // iterator
    std::cout << "Highest: " << *best << "\n";

    int toppers = std::count(marks.begin(), marks.end(), 91);
    std::cout << "Students with 91: " << toppers << "\n";

    auto it = std::find(marks.begin(), marks.end(), 66);
    if (it != marks.end())
        std::cout << "66 found at position " << (it - marks.begin()) << "\n";
    return 0;
}
Sorted: 55 66 73 78 84 91 91 Highest: 91 Students with 91: 2 66 found at position 1

No manual memory management, no hand-written sorting loop — and each line says what it does.

Types of containers

Sequence containers — elements in the order you put them

  • [vector](/tutorial/cpp/vector/) — dynamic array; fast access by index, fast add/remove at the end.
  • [deque](/tutorial/cpp/list-deque/) — double-ended queue; fast add/remove at both ends.
  • [list](/tutorial/cpp/list-deque/) — doubly linked list; fast insert/erase anywhere once you have an iterator.
  • array — fixed-size array with STL features.
  • forward_list — singly linked list.

Associative containers — kept sorted by key

  • [set / multiset](/tutorial/cpp/set-map/) — sorted values (unique / duplicates allowed).
  • [map / multimap](/tutorial/cpp/set-map/) — sorted key → value pairs.

Unordered containers — hash tables

  • unordered_set, unordered_map — average O(1) lookup, no ordering.

Container adapters — restricted interfaces

  • [stack](/tutorial/cpp/stack-queue/) (LIFO), [queue](/tutorial/cpp/stack-queue/) (FIFO), [priority_queue](/tutorial/cpp/stack-queue/) (largest first).

Which container should I use?

You need…Use
A list of items, mostly added at the end, accessed by indexvector
Fast insert/remove at the front and backdeque
Unique items kept sorted (e.g. roll numbers)set
Look up a value by key, in sorted key order (e.g. name → marks)map
Fastest lookup by key, order doesn't matterunordered_map
Last-in-first-out (undo, bracket matching)stack
First-in-first-out (token queue, BFS)queue
Always take the highest/lowest priority nextpriority_queue

When in doubt, start with vector.

A second example: map

C++
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> marks;
    marks["Priya"] = 91;
    marks["Aman"]  = 78;
    marks["Ravi"]  = 66;

    for (const auto& [name, m] : marks)          // C++17 structured binding
        std::cout << name << " -> " << m << "\n";
    return 0;
}
Aman -> 78 Priya -> 91 Ravi -> 66

The map keeps names in alphabetical order automatically.

Why use the STL?

  • Correct: used by millions of programmers and tested by compiler vendors.
  • Fast: algorithms have guaranteed complexity, e.g. sort is O(n log n).
  • Generic: the same vector works for int, std::string or your own Student class.
  • Less code: fewer loops and no manual new/delete.
  • Required knowledge: used in almost every C++ interview, competitive programming and real project.

Common mistakes

  • Forgetting the header: <vector>, <map>, <algorithm> must be included separately.
  • Dereferencing end() — it points *past* the last element, not to it.
  • Using find on a map's range instead of map.find(key) (much slower).
  • Modifying a vector (e.g. push_back) while holding iterators to it — they may become invalid.
  • Using operator[] on a map just to check if a key exists; it inserts the key. Use find or count.
🏋️ Practice

Read 8 marks into a vector<int>. Print them sorted in descending order (hint: std::greater<int>()), print the average using std::accumulate from <numeric>, and count how many are 33 or above using std::count_if with a lambda.

Summary

  • The STL provides ready-made containers, iterators, algorithms and function objects.
  • Algorithms work on iterator ranges, so they are independent of the container.
  • Sequence, associative, unordered and adapter containers each suit different jobs.
  • Start with vector; use map/unordered_map for key-based lookup.
  • Include the right header and never dereference end().

Next: vector → list and deque → stack and queue → set and map → iterators → algorithms.

Frequently Asked Questions

What is STL in C++?
STL (Standard Template Library) is the part of the C++ standard library that provides ready-made, tested templates for common data structures (containers like vector, list, map, set) and algorithms (like sort, find, count) that work together through iterators.
What are the components of STL?
The main components are containers (which store data), iterators (which move through the data), algorithms (which process the data) and function objects or lambdas (which customise the algorithms, for example a comparison for sorting). Container adapters like stack and queue are built on top of containers.
What are the types of containers in STL?
Sequence containers keep elements in order: vector, deque, list, forward_list, array. Associative containers keep elements sorted by key: set, multiset, map, multimap. Unordered containers use hashing: unordered_set, unordered_map. Container adapters: stack, queue, priority_queue.
Which STL container should I use by default?
Use std::vector unless you have a reason not to. It stores elements contiguously, is cache-friendly, supports fast random access and fast insertion at the end. Choose map/unordered_map for key–value lookups, set for unique sorted values, and deque when you need fast insertion at both ends.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicVector in C++ STL Your progress: 53 / 81 (65%) · Lesson 54 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free