OOP Standard Template Library (STD)

 
STL (Standard Template Library) is a powerful library in C++ that provides:

Ready-made classes and functions for common data structures and algorithms.
Generic programming — works with any data type using templates.


Components of STL

STL has four main components:


Component

Description

Example

1. Containers

Store data

vector, list, set, map

2. Algorithms

Perform operations on data

sort(), find(), count()

3. Iterators

Access elements in containers

begin(), end()

4. Functors

Function objects used with algorithms

greater<int>()



CONTAINERS

Containers are data structures that hold collections of elements.

They are of 3 types:

Type

Examples

Description

Sequence Containers

vector, list, deque

Store data sequentially

Associative Containers

set, map, multiset, multimap

Store data in sorted order with keys

Unordered Containers

unordered_set, unordered_map

Store data using hash tables



Example: Vector (Dynamic Array)

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

int main() {
    vector<int> v = {10, 20, 30};

    v.push_back(40);   // Add element
    v.pop_back();      // Remove last element

    cout << "Vector elements: ";
    for (int x : v)
        cout << x << " ";

    cout << "\nSize: " << v.size() << endl;

    return 0;
}

Output:
Vector elements: 10 20 30 
Size: 3


Example 2: Set (Unique Sorted Elements)

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

int main() {
    set<int> s = {30, 10, 20, 10};

    cout << "Set elements: ";
    for (int x : s)
        cout << x << " "; // automatically sorted and unique

    return 0;
}

Output:

Set elements: 10 20 30



Post a Comment

0 Comments