Skip to content
C++

STL Containers

Common container operations.

By EZ4Code Team
stlcontainer

Code

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <string>

int main() {
    // vector
    std::vector<int> v = {1, 2, 3};
    v.push_back(4);
    v.pop_back();
    v.size();
    v.empty();
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";

    // map (ordered)
    std::map<std::string, int> m;
    m["alice"] = 30;
    m["bob"] = 25;
    m.insert({"charlie", 35});
    for (const auto& [key, val] : m)
        std::cout << key << ":" << val << " ";
    std::cout << "\n";

    // unordered_map (hash)
    std::unordered_map<int, std::string> um;
    um[1] = "one";
    um[2] = "two";
    if (um.count(1)) std::cout << "found\n";

    // set
    std::set<int> s = {3, 1, 4, 1, 5};
    s.insert(2);
    s.erase(1);
    for (int x : s) std::cout << x << " "; // 2 3 4 5
    std::cout << "\n";

    // Find
    auto it = m.find("alice");
    if (it != m.end()) std::cout << it->second << "\n";

    return 0;
}

Explanation

vector is a dynamic array; map is ordered key-value pairs; unordered_map is a hash table; set is an ordered collection.

More C++ Snippets