Containers

std::array  (from <array> )

  • Fixed-size wrapper over arrays.

  • Arrays from C restrict its copy and easily decay into pointers, they probably suffer from an excess of optimization.

  • To overcome some of these issues with language built-in arrays, C++ provides an alternative array type as a standard container. It is a type template (a class template, in fact) defined in header <array> .

#include <iostream>
#include <array>

int main() {
    array<int,3> my_array {10,20,30};
    for (int i=0; i < my_array.size(); ++i)
        ++my_array[i];
        for (int elem : my_array)
            std::cout << elem << '\n';
}

std::vector  (from <vector> )

  • dynamic growth

  • contiguous memory

  • similar to C# List<T>

#include <vector>

std::vector<int> v;

v.push_back(1);
v.push_back(2);

int x = v[0];

std::span  (C++20)

  • Non-owning view over contiguous memory.

    • Caio: Same as Odin's Slices?

  • No memory allocation.

#include <span>

void Process(std::span<int> data)
{
    for (int v : data)
        printf("%d\n", v);
}

int arr[4] = {1,2,3,4};

Process(arr);

std::deque

  • Double-ended queue.

  • Not contiguous.

#include <deque>

std::deque<int> d;

d.push_front(1);
d.push_back(2);

std::unordered_map

  • Hash map.

#include <unordered_map>

std::unordered_map<int,int> map;

map[5] = 10;