Lesson 57 of 60 – STL Introduction
95%

STL Introduction in C++

STL stands for Standard Template Library. It is a collection of ready-to-use classes, containers, iterators, and algorithms provided by C++.

STL helps programmers write efficient and reusable programs without creating common data structures and algorithms from scratch.

Note: STL is one of the most important parts of modern C++ programming. It provides useful containers such as vector, map, and set, along with algorithms such as sorting and searching.

1. What is STL?

STL means Standard Template Library. It provides generic components that can work with different data types.

For example, instead of creating your own dynamic array, you can use std::vector.

#include <vector>

std::vector<int> numbers;

The same vector can be used with different data types.

2. Main Parts of STL

The main parts of STL include:

  • Containers – store collections of data.
  • Iterators – provide a way to access elements.
  • Algorithms – perform operations such as sorting and searching.
  • Function Objects – objects that can behave like functions.
  • Allocators – support memory allocation for containers.

Containers, iterators, and algorithms are especially important for beginners.

3. Why Use STL?

STL provides reusable and tested components for common programming tasks.

  • Reduces the amount of code.
  • Provides ready-to-use data structures.
  • Provides common algorithms.
  • Supports generic programming.
  • Makes programs easier to maintain.
  • Works with many different data types.

4. STL Containers

Containers are objects used to store collections of values.

Common STL containers include:

Container Purpose
vector Dynamic array.
list Doubly linked list.
deque Double-ended sequence.
set Stores unique sorted values.
map Stores key-value pairs.
stack Last-in, first-out structure.
queue First-in, first-out structure.

5. STL Algorithms

STL provides many algorithms for common operations.

Some commonly used algorithms are:

  • sort()
  • find()
  • reverse()
  • count()
  • max()
  • min()
  • binary_search()

Most standard algorithms are available through the <algorithm> header.

6. The vector Container

A vector is a dynamic array that can automatically change its size.

#include <vector>

std::vector<int> numbers;

numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

The vector now contains three integers.

7. Accessing Vector Elements

Vector elements can be accessed using indexes.

#include <iostream>
#include <vector>

int main() {

    std::vector<int> numbers = {
        10, 20, 30
    };

    std::cout <<
        numbers[0];

    return 0;
}

The first element has index 0.

8. push_back()

The push_back() function adds an element to the end of a vector.

std::vector<int> numbers;

numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

The vector becomes:

10 20 30

9. size() Function

The size() function returns the number of elements in a container.

std::vector<int> numbers = {
    10, 20, 30, 40
};

std::cout <<
    numbers.size();

Output:

4

10. Iterators

An iterator is an object that can be used to move through elements of an STL container.

std::vector<int> numbers = {
    10, 20, 30
};

for(
    auto it = numbers.begin();
    it != numbers.end();
    ++it
) {

    std::cout <<
        *it << " ";
}

begin() returns an iterator to the first element and end() represents the position just after the last element.

11. range-based for Loop

A range-based for loop provides a simple way to traverse an STL container.

std::vector<int> numbers = {
    10, 20, 30
};

for(int value : numbers) {

    std::cout <<
        value << " ";
}

This is often easier to read than manually using iterators.

12. sort() Algorithm

The sort() algorithm sorts elements in ascending order by default.

#include <algorithm>
#include <vector>

std::vector<int> numbers = {
    40, 10, 30, 20
};

std::sort(
    numbers.begin(),
    numbers.end()
);

The resulting order is:

10 20 30 40

13. find() Algorithm

The find() algorithm searches for a value in a range.

#include <algorithm>
#include <vector>

std::vector<int> numbers = {
    10, 20, 30
};

auto result =
    std::find(
        numbers.begin(),
        numbers.end(),
        20
    );

if(
    result != numbers.end()
) {

    std::cout <<
        "Found";
}

14. reverse() Algorithm

The reverse() algorithm reverses the elements in a range.

std::vector<int> numbers = {
    10, 20, 30
};

std::reverse(
    numbers.begin(),
    numbers.end()
);

The vector becomes:

30 20 10

15. count() Algorithm

The count() algorithm counts how many times a value occurs in a range.

std::vector<int> numbers = {
    10, 20, 10, 30, 10
};

int total =
    std::count(
        numbers.begin(),
        numbers.end(),
        10
    );

std::cout <<
    total;

Output:

3

16. The set Container

A set stores unique values. Its elements are maintained in sorted order according to its comparison rules.

#include <set>

std::set<int> numbers;

numbers.insert(30);
numbers.insert(10);
numbers.insert(20);
numbers.insert(10);

The duplicate 10 is not stored twice.

17. The map Container

A map stores data as key-value pairs.

#include <map>

std::map<int, std::string> students;

students[101] =
    "Rahul";

students[102] =
    "Priya";

Here, the student ID is the key and the student's name is the value.

18. The pair Type

The std::pair type stores two related values.

#include <utility>

std::pair<int, std::string> student;

student.first = 101;
student.second = "Rahul";

The first value is accessed using first and the second using second.

19. The stack Container

A stack follows the LIFO principle: Last In, First Out.

#include <stack>

std::stack<int> numbers;

numbers.push(10);
numbers.push(20);
numbers.push(30);

std::cout <<
    numbers.top();

Output:

30

20. The queue Container

A queue follows the FIFO principle: First In, First Out.

#include <queue>

std::queue<int> numbers;

numbers.push(10);
numbers.push(20);
numbers.push(30);

std::cout <<
    numbers.front();

Output:

10

21. deque Container

A deque is a double-ended queue. It supports efficient insertion and removal at both ends.

#include <deque>

std::deque<int> numbers;

numbers.push_back(20);
numbers.push_front(10);

for(int value : numbers) {

    std::cout <<
        value << " ";
}

Output:

10 20

22. Useful STL Functions

Many STL containers provide common member functions.

Function Purpose
size() Returns the number of elements.
empty() Checks whether the container is empty.
clear() Removes elements from containers that support it.
begin() Returns an iterator to the beginning.
end() Returns an iterator representing the end position.
insert() Adds elements according to the container's rules.
erase() Removes elements according to the container's interface.

23. STL with Strings

STL algorithms can also be used with strings because strings provide iterators.

#include <algorithm>
#include <iostream>
#include <string>

int main() {

    std::string name =
        "rahul";

    std::reverse(
        name.begin(),
        name.end()
    );

    std::cout <<
        name;

    return 0;
}

The same general algorithm can operate on different suitable ranges.

24. STL and Generic Programming

STL is based heavily on templates. This allows many containers and algorithms to work with different data types.

std::vector<int> numbers = {
    10, 20, 30
};

std::vector<double> prices = {
    10.5, 20.5, 30.5
};

std::vector<std::string> names = {
    "Rahul",
    "Priya"
};

The same container concept can be used with different types.

25. STL Header Files

Different STL components are declared in different standard headers.

Header Examples
<vector> vector
<list> list
<deque> deque
<set> set, multiset
<map> map, multimap
<stack> stack
<queue> queue, priority_queue
<algorithm> sort, find, reverse, count

26. Common STL Mistakes

  • Forgetting to include the required header.
  • Forgetting the std:: namespace qualifier when needed.
  • Accessing a vector using an invalid index.
  • Dereferencing an iterator that is equal to end().
  • Assuming that every container stores elements in the same order.
  • Using the wrong container for a particular requirement.
  • Modifying a container while using an iterator without understanding iterator invalidation rules.
  • Confusing stack LIFO behavior with queue FIFO behavior.

27. Choosing the Right Container

Different containers are designed for different types of operations.

Requirement Common Choice
Dynamic sequence vector
Unique sorted values set
Key-value data map
LIFO processing stack
FIFO processing queue
Insertion/removal at both ends deque

The appropriate choice depends on the operations your program needs to perform.

28. Best Practices with STL

  • Choose a container according to the required operations.
  • Prefer STL containers instead of manually managing basic dynamic collections.
  • Use standard algorithms when they match the task.
  • Use range-based for loops when they improve readability.
  • Use const when data should not be modified.
  • Check iterator validity before dereferencing.
  • Understand the performance characteristics of containers and algorithms.
  • Keep STL code simple and readable.

29. Practical STL Example

#include <algorithm>
#include <iostream>
#include <vector>

int main() {

    std::vector<int> marks = {
        75, 92, 68, 85, 92
    };

    std::sort(
        marks.begin(),
        marks.end()
    );

    std::cout <<
        "Sorted marks: ";

    for(int mark : marks) {

        std::cout <<
            mark << " ";
    }

    int total =
        std::count(
            marks.begin(),
            marks.end(),
            92
        );

    std::cout <<
        "\n92 occurs "
        << total
        << " times.";

    return 0;
}

This example uses a vector, the sort() algorithm, a range-based loop, and the count() algorithm.

30. STL – Final Summary

Concept Meaning
STL Standard Template Library.
Container Stores collections of data.
Iterator Provides a way to access elements in a range.
Algorithm Performs common operations on ranges.
vector Dynamic array-like sequence container.
set Stores unique ordered values.
map Stores key-value pairs.
stack LIFO container adaptor.
queue FIFO container adaptor.
sort() Sorts elements in a range.
find() Searches for a value in a range.
#include <algorithm>
#include <iostream>
#include <vector>

int main() {

    std::vector<int> numbers = {
        40, 10, 30, 20
    };

    std::sort(
        numbers.begin(),
        numbers.end()
    );

    for(int number : numbers) {

        std::cout <<
            number << " ";
    }

    return 0;
}

STL provides powerful reusable tools for C++ programming. Once you understand containers, iterators, and algorithms, you can solve many programming problems with less code and clearer logic.

📌 Key Points

  • STL stands for Standard Template Library.
  • STL provides containers, iterators, algorithms, and other reusable components.
  • vector is a commonly used dynamic sequence container.
  • set stores unique ordered values.
  • map stores key-value pairs.
  • stack follows LIFO behavior.
  • queue follows FIFO behavior.
  • Iterators provide access to elements in container ranges.
  • Algorithms such as sort(), find(), and reverse() simplify common operations.
  • STL uses templates to provide reusable components for different data types.

🧠 Quick Quiz

Question: What does STL stand for in C++?