C++C++

C++: Data structures – code examples

Contents

Working with std::vector

Data structures#vector#array#sort#accumulateCompare in all languages
Use case: Manage collections of values: add, sort, sum up.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> zahlen{5, 3, 8, 1};
    zahlen.push_back(10);
    std::sort(zahlen.begin(), zahlen.end());
    for (int z : zahlen) std::cout << z << ' ';
    std::cout << "\nSum: " << std::accumulate(zahlen.begin(), zahlen.end(), 0) << '\n';
}

The analogue of a list is std::vector. Sorting and summing are done by algorithms from <algorithm> and <numeric> using iterators.

std::map

Data structures#map#dictionary#hashmap#structured-bindingCompare in all languages
Use case: Store mappings, e.g. configurations, counters or lookup tables.
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> person{{"Ada", 36}, {"Bob", 25}};
    person["Cy"] = 41;
    for (const auto& [name, alter] : person)
        std::cout << name << " = " << alter << '\n';
    if (auto it = person.find("Dora"); it == person.end())
        std::cout << "Dora not found\n";
}

std::map is sorted by key; find returns an iterator (end() means: not present). For faster access without sorting, use std::unordered_map.

Sorting with a lambda comparison

Data structures#sort#lambda#struct#vector
Use case: Order records by a field, e.g. users by age or products by price.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Nutzer { std::string name; int alter; };

int main() {
    std::vector<Nutzer> nutzer{{"Ada", 36}, {"Bob", 25}, {"Cy", 41}};
    std::sort(nutzer.begin(), nutzer.end(),
              [](const Nutzer& a, const Nutzer& b) { return a.alter < b.alter; });
    for (const auto& n : nutzer) std::cout << n.name << ' ' << n.alter << '\n';
}

The lambda is a "less-than" comparison; std::sort sorts in place. For stability (equal elements keep their order), there is std::stable_sort.

Deleting elements from a vector

Data structures#erase_if#vector#filter
Use case: Remove invalid or unwanted entries from a list.
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5, 6};
    std::erase_if(v, [](int x) { return x % 2 == 0; });   // C++20
    for (int x : v) std::cout << x << ' ';   // 1 3 5
    std::cout << '\n';
}

std::erase_if (C++20) replaces the older erase-remove idiom v.erase(std::remove_if(...), v.end()). Never delete with erase inside a range-for loop.