</>
Skip to content
C++ lessons (35/42)

C++ — STL

Containers overview

ContainerDescriptionHeader
vectorDynamic array<vector>
listDoubly linked list<list>
dequeDouble-ended queue<deque>
setSorted unique elements<set>
mapSorted key-value pairs<map>
unordered_setHash set<unordered_set>
unordered_mapHash map<unordered_map>
stackLIFO stack<stack>
queueFIFO queue<queue>
priority_queueHeap<queue>

vector

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

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};

    nums.push_back(6);       // Add to end
    nums.pop_back();          // Remove from end
    nums.insert(nums.begin(), 0); // Insert at beginning

    cout << "Size: " << nums.size() << endl;
    cout << "Front: " << nums.front() << endl;
    cout << "Back: " << nums.back() << endl;

    for (const auto &n : nums) {
        cout << n << " ";
    }
    cout << endl;

    return 0;
}

map

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

int main() {
    map<string, int> scores;
    scores["Alice"] = 95;
    scores["Bob"] = 87;
    scores["Charlie"] = 92;

    // Find
    if (scores.find("Alice") != scores.end()) {
        cout << "Alice: " << scores["Alice"] << endl;
    }

    // Iterate
    for (const auto &[name, score] : scores) {
        cout << name << ": " << score << endl;
    }

    // Count
    cout << "Size: " << scores.size() << endl;

    return 0;
}

set

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

int main() {
    set<int> unique;
    unique.insert(3);
    unique.insert(1);
    unique.insert(4);
    unique.insert(1); // Duplicate — ignored

    for (const auto &n : unique) {
        cout << n << " ";
    }
    cout << endl; // 1 3 4 (sorted)

    cout << "Contains 3: " << unique.count(3) << endl;
    cout << "Contains 5: " << unique.count(5) << endl;

    return 0;
}

Algorithms

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

int main() {
    vector<int> nums = {5, 2, 8, 1, 9, 3};

    // Sort
    sort(nums.begin(), nums.end());
    cout << "Sorted: ";
    for (int n : nums) cout << n << " ";
    cout << endl;

    // Reverse
    reverse(nums.begin(), nums.end());

    // Find
    auto it = find(nums.begin(), nums.end(), 8);
    if (it != nums.end()) {
        cout << "Found 8 at index " << (it - nums.begin()) << endl;
    }

    // Count
    cout << "Count of 3: " << count(nums.begin(), nums.end(), 3) << endl;

    // Accumulate
    int sum = accumulate(nums.begin(), nums.end(), 0);
    cout << "Sum: " << sum << endl;

    // Min/Max
    cout << "Min: " << *min_element(nums.begin(), nums.end()) << endl;
    cout << "Max: " << *max_element(nums.begin(), nums.end()) << endl;

    return 0;
}

Iterators

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

int main() {
    vector<int> nums = {10, 20, 30, 40, 50};

    // Forward iteration
    for (auto it = nums.begin(); it != nums.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    // Reverse iteration
    for (auto it = nums.rbegin(); it != nums.rend(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    // Const iteration
    for (auto it = nums.cbegin(); it != nums.cend(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}

Lambda with algorithms

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

int main() {
    vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Filter even numbers
    vector<int> evens;
    copy_if(nums.begin(), nums.end(), back_inserter(evens),
            [](int n) { return n % 2 == 0; });

    cout << "Evens: ";
    for (int n : evens) cout << n << " ";
    cout << endl;

    // Transform
    vector<int> squared(nums.size());
    transform(nums.begin(), nums.end(), squared.begin(),
              [](int n) { return n * n; });

    cout << "Squared: ";
    for (int n : squared) cout << n << " ";
    cout << endl;

    // For each
    for_each(nums.begin(), nums.end(), [](int n) {
        cout << n * 2 << " ";
    });
    cout << endl;

    return 0;
}

string as a container

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string s = "Hello, World!";

    // Iterator-based
    for (auto it = s.begin(); it != s.end(); ++it) {
        *it = toupper(*it);
    }
    cout << s << endl; // HELLO, WORLD!

    // Algorithms work on strings
    string t = "hello";
    sort(t.begin(), t.end());
    cout << t << endl; // ehllo

    return 0;
}

Choosing the right container

NeedContainer
Fast random accessvector
Frequent insert/delete at frontdeque
Sorted unique elementsset
Key-value lookupmap or unordered_map
Fast lookup, no orderingunordered_set or unordered_map
LIFOstack
FIFOqueue
Priority processingpriority_queue

Mini Practice

Write C++ code that:

  1. Uses vector to store and sort a list of numbers
  2. Uses map to count word frequencies in a string
  3. Uses set to find unique elements from two vectors
  4. Uses for_each with a lambda to print all elements

Up Next

Congratulations! You've completed the C++ fundamentals. Continue exploring advanced topics like smart pointers, concurrency, and template metaprogramming.

Related Topics

Frequently Asked Questions about STL

What is STL in C++?

STL is a fundamental concept in C++. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn STL?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn STL.

Why is STL important in C++?

STL is essential for C++ development. Understanding this concept will help you write better code and solve real-world problems more effectively.