Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C++ Programming Tutorial / Chapter 4: Templates, Exceptions & The STL
CPP ⏱ 14 min read

Standard Template Library (STL) Overview & std::vector

The Standard Template Library (STL) is the crown jewel of C++, providing production-grade, highly optimized data structures and algorithms.

What is it?

The STL consists of Containers (vector, map, set), Iterators (pointers to container elements), and Algorithms (sort, find, count). `std::vector` is a dynamic, automatically resizable array.

Why is it used?

`std::vector` is the default go-to container in C++. It handles heap memory allocation, resizing, and deallocation automatically with zero memory leaks.

Detailed Explanation

Vector Operations: • Adding elements: `.push_back(x)` or `.emplace_back(x)` (constructs in place). • Removing elements: `.pop_back()`. • Accessing: • `vec[i]`: Fast, unchecked access. • `vec.at(i)`: Safe access with bounds checking (throws `std::out_of_range`). • Size & Capacity: `.size()`, `.empty()`, `.capacity()`, `.clear()`. • Memory Allocation: When capacity is exceeded, vector doubles its internal buffer automatically.

Syntax Structure

Syntax Blueprint
#include <vector>
std::vector<int> numbers = {1, 2, 3};
numbers.push_back(4);

Code Example

CPP Code
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    // Initialize dynamic vector of course fees
    std::vector<int> fees = {2500, 1800, 5397, 2500, 2000};
    
    // Append element dynamically
    fees.push_back(3200);
    
    std::cout << "=== Vector Operations Demonstration ===\n";
    std::cout << "Total items in vector: " << fees.size() << "\n";
    
    // STL Algorithm: Sort ascending
    std::sort(fees.begin(), fees.end());
    
    std::cout << "Sorted Fees: ";
    for (const auto &fee : fees) {
        std::cout << "₹" << fee << " ";
    }
    std::cout << "\n";
    
    // Safe element access with .at()
    try {
        std::cout << "First fee:  ₹" << fees.at(0) << "\n";
        std::cout << "Last fee:   ₹" << fees.back() << "\n";
    } catch (const std::out_of_range &e) {
        std::cerr << "Out of bounds: " << e.what() << "\n";
    }
    
    return 0;
}

Explanation of the Code

• `std::vector<int>` manages dynamic memory automatically. • `std::sort(fees.begin(), fees.end())` sorts the vector using IntroSort (hybrid of QuickSort, HeapSort, and InsertionSort). • `.back()` accesses the last element cleanly.

Expected Output

=== Vector Operations Demonstration === Total items in vector: 6 Sorted Fees: ₹1800 ₹2000 ₹2500 ₹2500 ₹3200 ₹5397 First fee: ₹1800 Last fee: ₹5397

Real-World Application

Used across game development to store entities, bullets, and render queues.

Common Mistakes to Avoid

• Using raw C-style arrays (`int arr[100]`) instead of `std::vector` or `std::array`. • Reallocating in a loop without using `vec.reserve()` when the number of elements is known upfront.

Quick Practice Challenge

Create a vector of strings containing 3 names, sort them alphabetically using `std::sort`, and print them.

Key Takeaways

• `std::vector` is a dynamic, resizable array on the heap. • Use `.push_back()` to append and `.size()` to check count. • Combine with STL algorithms like `std::sort()` and `std::find()`.