JSTAcademy
0 XP
Dashboard
Crash Courses
STL: Vector, Map, String & Algorithms
40 min
Masters+180 XP
Crash Courses · Masters

STL: Vector, Map, String & Algorithms

The Standard Template Library — containers, iterators, and algorithms
40 min read+180 XP on completionCert: C++ Crash Course
Tap any word in the text below to start reading from there.

STL: Vector, Map, String & Algorithms

std::vector

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {3, 1, 4, 1, 5, 9};

    v.push_back(2);               // append
    v.insert(v.begin(), 0);       // prepend
    v.erase(v.begin() + 1);       // remove element at index 1

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

    // Range-based for
    for (const auto& n : v) {
        std::cout << n << " ";
    }
    return 0;
}

std::map

#include <map>
#include <string>

int main() {
    std::map<std::string, int> scores;
    scores["Alice"] = 95;
    scores["Bob"]   = 87;
    scores["Carol"] = 91;

    // Lookup
    if (scores.count("Alice")) {
        std::cout << "Alice: " << scores["Alice"] << std::endl;
    }

    // Iterate (always sorted by key)
    for (const auto& [name, score] : scores) { // C++17 structured bindings
        std::cout << name << ": " << score << std::endl;
    }

    // find returns iterator
    auto it = scores.find("Bob");
    if (it != scores.end()) {
        std::cout << "Found: " << it->second << std::endl;
    }
    return 0;
}

std::string

#include <string>

std::string s = "Hello, World!";

std::cout << s.length() << std::endl;      // 13
std::cout << s.substr(7, 5) << std::endl;  // World
std::cout << s.find("World") << std::endl; // 7

s.replace(7, 5, "C++");
std::cout << s << std::endl; // Hello, C++!

// split workaround (no built-in split)
#include <sstream>
std::istringstream iss("a b c");
std::string token;
while (iss >> token) std::cout << token << "\n";

STL Algorithms

#include <algorithm>
#include <vector>
#include <numeric>

std::vector<int> v = {5, 2, 8, 1, 9, 3};

// Sort
std::sort(v.begin(), v.end());                        // ascending
std::sort(v.begin(), v.end(), std::greater<int>());   // descending

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

// Count
int fives = std::count(v.begin(), v.end(), 5);

// Transform (like map in functional programming)
std::vector<int> doubled(v.size());
std::transform(v.begin(), v.end(), doubled.begin(), [](int x) { return x * 2; });

// Accumulate (fold/reduce)
int sum = std::accumulate(v.begin(), v.end(), 0); // 0 = initial value

// Remove duplicates (sort first)
std::sort(v.begin(), v.end());
auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end());
0%