Implementing C++ STL containers in pure C — what I learned
I've been experimenting with implementing C++ STL-style containers (vector, list, deque, set, map, stack, queue, priority_queue, unordered_set, unordered_map) as a single-header C library using C99 macros and variadic dispatch. The goal was to see how close you can get to the C++ STL interface in pure C — same function names like push_back , insert , erase , find , begin / end — without requiring a C++ compiler. A few interesting design challenges came up: 1. Bracket access ( v[i] ) For VECTOR and DEQUE , the handle is just a <type>* pointing into the data region, so v[i] works naturally as pointer arithmetic. Metadata (size, capacity) is stored before the pointer address. This also means you can pass a vector directly to qsort or bsearch with no wrapper. ```c VECTOR(int) v = new_vector(int); for (int i = 0; i < 10; i++) push_back(v, i); qsort(v, size(v), sizeof(int), my_cmp); // just works printf("%d", v[3]); // bracket access destroy(v); ``` 2. Variadic overloading in C Using macro a
Continue reading on Reddit Programming
Opens in a new tab



