</>
CompilerOnline
Open Interactive Editor

C++ Standard Template Library (STL)

Understanding C++ STL

The Standard Template Library (STL) is a set of C++ template classes providing common programming data structures and functions such as lists, stacks, vectors, etc. It provides a foundation of reusable, highly optimized code.

Core Components:

  • Containers: Used to manage collections of objects (e.g. vector, map, set).
  • Algorithms: Operations applied on container contents (e.g. sort, binary_search, reverse).
  • Iterators: Connectors that step through container contents.

Containers are classified as sequence containers (like vector and list) or associative containers (like set and map, which use red-black trees under the hood). This classification guarantees specific performance levels for insertions and searches.

By using STL algorithms, you avoid writing boilerplate sorting and searching code, relying instead on library implementations that have been highly optimized by compiler writers over decades.

Binary Searching in STL

The STL <algorithm> header provides sorted search functions like std::binary_search, which performs a fast O(log N) lookup on a sorted collection.

cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
    std::vector<int> nums = {9, 2, 7, 1};
    std::sort(nums.begin(), nums.end());
    if (std::binary_search(nums.begin(), nums.end(), 7)) {
        std::cout << "Found 7!" << std::endl;
    }
    return 0;
}
cpp
#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v = {4, 2, 5, 1, 3};
    std::sort(v.begin(), v.end());
    std::cout << "Sorted vector: ";
    for(int x : v) std::cout << x << " ";
    std::cout << std::endl;
    return 0;
}