GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR

⚡ Lesson 8: STL & Memory Management

⏱️ Estimated time: 40 minutes | Difficulty: Advanced

Advanced Territory

C++ gives you total control over memory. Using the STL and smart pointers is crucial for writing safe, modern C++ code.

Standard Template Library (STL)

The STL provides powerful containers, algorithms, and iterators that save you from reinventing the wheel.

Vectors (Dynamic Arrays)

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

vector<int> nums = {1, 2, 3, 4, 5};
nums.push_back(6);       // Add to end
nums.pop_back();          // Remove last
cout << nums.size();     // 5
cout << nums[0];         // 1

// Range-based for loop
for (int n : nums) {
    cout << n << " ";
}

Maps (Key-Value Pairs)

#include <map>

map<string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;

for (auto& [name, age] : ages) {
    cout << name << ": " << age << endl;
}

STL Algorithms

#include <algorithm>

vector<int> v = {5, 2, 8, 1, 9};
sort(v.begin(), v.end());         // 1 2 5 8 9
reverse(v.begin(), v.end());      // 9 8 5 2 1

auto it = find(v.begin(), v.end(), 5);
if (it != v.end()) cout << "Found!";

int maxVal = *max_element(v.begin(), v.end());
int minVal = *min_element(v.begin(), v.end());

Smart Pointers (Modern C++)

#include <memory>

// unique_ptr: exclusive ownership
auto ptr1 = make_unique<int>(42);
cout << *ptr1;  // 42
// Automatically freed when out of scope!

// shared_ptr: shared ownership
auto ptr2 = make_shared<string>("Hello");
auto ptr3 = ptr2;  // Both point to same string
cout << *ptr2 << endl;
// Freed when last shared_ptr goes away

💡 Best Practice: In modern C++, prefer unique_ptr and shared_ptr over raw pointers (new/delete). They automatically free memory!

✅ Quick Quiz

❓ What is a vector in C++?

❓ What does unique_ptr do?

❓ Which function sorts a vector?

← Previous 🎉 Back to All Lessons