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
Syntax Structure
#include <vector>
std::vector<int> numbers = {1, 2, 3};
numbers.push_back(4);
Code Example
#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
Expected Output
Real-World Application
Used across game development to store entities, bullets, and render queues.
Common Mistakes to Avoid
Quick Practice Challenge
Create a vector of strings containing 3 names, sort them alphabetically using `std::sort`, and print them.