COMS W4995 C++ Deep Dive for C Programmers

Index of 2025-9/code/10

Parent directory
Makefile
stl.cpp

Makefile

CC  = g++
CXX = g++

CFLAGS   = -g -Wall
CXXFLAGS = -g -Wall -std=c++20

executables = stl

.PHONY: default
default: $(executables)

stl: stl.o

.PHONY: clean
clean:
	rm -f *~ a.out core *.o $(executables)

.PHONY: all
all: clean default

stl.cpp

#include <array>
#include <vector>
#include <deque>
#include <list>
#include <forward_list>
#include <iostream>
using namespace std;

template <typename T, size_t N>
struct Array {

    // typedef T value_type;
    using value_type = T;

    // T(&)[N] is a reference to array of N elements of type T
    using TA = T(&)[N];

    T& operator[](int i) { return a[i]; }
    const T& operator[](int i) const { return a[i]; }

    constexpr size_t size() const { return N; }
    TA underlying() { return a; }

    T a[N];
};

void print_int(int x)  { cout << x << ' '; }

int main() {

    // 1. C Arrays
    //
    int a[5] { 100, 101, 102, 103, 104 };
    size_t n = sizeof(a) / sizeof(a[0]);
    for (size_t i = 0; i < n; ++i)  { print_int(a[i]); }

    // 2. Array class template
    //
    // Array<int,5> v { 100, 101, 102, 103, 104 };
    // for (size_t i = 0; i < v.size(); ++i)  { print_int(v[i]); }
    
    // constexpr size_t n = sizeof(v.underlying()) /
    //                      sizeof(decltype(v)::value_type);
    // static_assert(v.size() == n);

    // 3. std::array
    //
    // std::array<int,5> v { 100, 101, 102, 103, 104 };
    // for (size_t i = 0; i < v.size(); ++i)  { print_int(v[i]); }

    // 4. std::vector
    //
    // vector<int> v { 100, 101, 102, 103, 104 };
    // v.push_back(105);
    // for (size_t i = 0; i < v.size(); ++i)  { print_int(v[i]); }

    // 5. std::deque
    //
    // deque<int> v { 100, 101, 102, 103, 104 };
    // v.push_front(99);
    // v.push_back(105);
    // for (size_t i = 0; i < v.size(); ++i)  { print_int(v[i]); }

    // 6. std::list
    //
    // list<int> v { 100, 101, 102, 103, 104 };
    // v.push_front(99);
    // v.push_back(105);
    // while (!v.empty())  {
    //     print_int(v.front());
    //     v.pop_front();
    // }

    // 7. std::forward_list
    //
    // forward_list<int> v { 100, 101, 102, 103, 104 };
    // v.push_front(99);
    // while (!v.empty())  {
    //     print_int(v.front());
    //     v.pop_front();
    // }
    // static_assert(sizeof(forward_list<int>) == 8);

    cout << '\n';
}