vector, map, set and algorithms

std::vector, std::map / std::unordered_map, std::set, and sorting and searching with <algorithm>.

Runs in Zerethon IDE · C++ (GCC 14) Official C++ documentation ↗
main.cpp
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <vector>

int main() {
    std::vector<int> scores{70, 95, 8, 82};
    scores.push_back(60);
    std::sort(scores.begin(), scores.end());
    for (int s : scores) std::cout << s << ' ';
    std::cout << "| size " << scores.size() << " sum " << std::accumulate(scores.begin(), scores.end(), 0) << '\n';

    std::sort(scores.begin(), scores.end(), [](int a, int b) { return a > b; });
    std::cout << scores.front() << ' ' << scores.back() << '\n';
    auto it = std::find(scores.begin(), scores.end(), 82);
    std::cout << (it != scores.end() ? "found 82" : "no 82") << '\n';

    std::map<std::string, int> ages{{"ada", 36}};
    ages["alan"] = 41;
    for (const auto& [name, age] : ages) std::cout << name << '=' << age << ' ';
    std::cout << ages.count("linus") << '\n';

    std::set<int> unique{3, 1, 3, 2};
    for (int u : unique) std::cout << u;
    std::cout << '\n';
}

Output

8 60 70 82 95 | size 5 sum 315
95 8
found 82
ada=36 alan=41 0
123
  • v[i] does not check the index; v.at(i) throws std::out_of_range instead of corrupting memory.
  • std::map keeps keys sorted; std::unordered_map is a hash map with no order.
  • map[key] inserts a default value when the key is missing — use count(), find() or contains() (C++20) to only look.