Chapter 33: STL Introduction

What is STL?

The Standard Template Library (STL) is a powerful library in C++ that provides a set of common classes and functions for data structures and algorithms. It includes:

Components of STL

1. Containers

Containers are data structures that store collections of objects. The main types of containers in STL are:

2. Iterators

Iterators are objects that point to elements in containers. They provide a way to access and traverse elements in containers.

3. Algorithms

Algorithms are functions that perform operations on containers. They are implemented as template functions and work with iterators.

Example Usage

Using a Vector Container

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

int main()
{
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Display elements
    for (int val : vec)
    {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    // Sort elements in descending order
    std::sort(vec.begin(), vec.end(), std::greater<int>());

    // Display sorted elements
    for (int val : vec)
    {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

Using an Iterator

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Use an iterator to traverse the vector
    for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
    {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

Using an Algorithm

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

int main()
{
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // Find an element
    auto it = std::find(vec.begin(), vec.end(), 3);
    if (it != vec.end())
    {
        std::cout << "Element found: " << *it << std::endl;
    }
    else
    {
        std::cout << "Element not found" << std::endl;
    }

    return 0;
}

Conclusion

The STL is a powerful tool in C++ that provides a wide range of functionalities for managing data structures and algorithms. Understanding and utilizing STL components can greatly enhance your programming efficiency and effectiveness.