Showing posts with label cpp_datastructure. Show all posts
Showing posts with label cpp_datastructure. Show all posts

Dec 15, 2025

[C++] [CppCon 2025] Implement the C++ Standard Library minute

Reference:

Implement the C++ Standard Library: Design, Optimisations, Testing while Implementing Libc++
[C++] Object Lifetimes reading minute

1)

1) tail padding.
2) if type is empty, it does not acquire address.

e.g.
struct Foo {
  int a; // 4
  char c; // 1 
  bool b; // 1
  // +2
};

enum class ErrCode : int {
 E1, E2, E3,
};

template<typename Val, Err>
struct Expected {
  union U {
  	[[no_unique_address]] Val val_;
	[[no_unique_address]] Err err_;
  };
  [[no_unique_address]] U value_;
  bool has_value_; 
};
Without `no_unique_address`, no tail padding,
sizeof(Expected<Foo, ErrCode>) == 12

With `no_unique_address`, 
bool has_value_;
can sneak into
U if U is of type Foo, `has_value_` would occupy Foo's tail padding,
thus:
sizeof(Expected<Foo, ErrCode>) == 8


2)

template<typename Val, Err>
struct Expected {
  union U {
  	[[no_unique_address]] Val val_;
	[[no_unique_address]] Err err_;
  };
  [[no_unique_address]] U value_;
  bool has_value_; 
  
  Expected(const Expected& other) :
  	has_value{other.has_value} {
	 if (has_value_) {
	 	std::construct_at(std::addressof(value_.val_), other.value_.val_);
	 } else {
	 	std::construct_at(std::addressof(value_.err_), other.value_.err_);
	 }
	}
};

Expected e1 = {Foo{}, true};
Expected e2 = e1;
assert(e2.has_value_); // Failed.
Why failed? Due to std::construct_at construct the value_ union's val_ and
zero out the padding, which has_value_ resides in due to `no_unique_address`.

Take away:

Don't mix no_unique_address with manual lifetime management
(union, construct_at, placement-new, std::bit_cast, std::start_lifetime_as, std::start_lifetime_as_array).


3)

Reference:
Segmented Iterators and Hierarchical Algorithms - Matthew H. Austern
https://lafstern.org/matt/segmented.pdf
Which is faster?
std::deque<int> d = ...

// 1
for (int& i : d) {
    i = std::clamp(i, 200, 500);
}

// 2 Faster due to using Segmented Iterators
std::ranges::for_each(d, [](int& i) {
    i = std::clamp(i, 200, 500);
});

Segmented Iterators:

template <class T> struct seg_array_iter
{
    // Local Iterator: position within the current segment (e.g., a vector<T>::iterator)
    vector<T>::iterator cur;
    
    // Segment Iterator: position among the segments (e.g., a vector<vector<T>*>::iterator)
    vector<vector<T>*>::iterator node;

    T& operator*() const { return *cur; }

    seg_array_iter& operator++() {
        // Standard increment: move to the next element in the current segment
        if (++cur == (**node).end()) {
            // End of segment reached: move to the next segment
            ++node;
            // Set the local iterator (cur) to the beginning of the new segment
            // or 0 (a null pointer equivalent for iterators) if it's the end.
            cur = *node ? (**node).begin() : 0;
        }
        return *this;
    }
    // ... other iterator operations like operator==, operator!=, etc.
};

template <class Iter, class T>
inline void fill (Iter first, Iter last, const T& x)
{
    typedef segmented_iterator_traits<Iter> Traits;
    
    // Dispatch call: The compiler chooses the segmented or nonsegmented helper 
    // based on the type of Traits::is_segmented_iterator (true_type or false_type).
    fill(first, last, x,
         typename Traits::is_segmented_iterator()); 
}

template <class SegIter, class T>
void fill (SegIter first, SegIter last, const T& x, true_type)
{
    typedef segmented_iterator_traits<SegIter> traits;

    // Decompose the full segmented iterators into segment and local iterators
    typename traits::segment_iterator sfirst = traits::segment (first);
    typename traits::segment_iterator slast = traits::segment (last);

    if (sfirst == slast) {
        // Case 1: Start and end are in the same segment. Use one local fill.
        fill(traits::local (first), traits::local (last), x);
    } else {
        // Case 2: Fill the *rest* of the starting segment
        fill(traits::local (first), traits::end(sfirst), x);

        // Case 3: Loop through all *middle* segments, filling them completely
        for (++sfirst; sfirst != slast; ++sfirst)
            fill(traits::begin(sfirst), traits::end(sfirst), x);

        // Case 4: Fill the *start* of the ending segment (sfirst now equals slast)
        fill(traits::begin(sfirst), traits::local (last), x);
    }
} 

Take away:

  • Use the most precise API for what you're trying to achieve.
    • insert_range instead of insert in a loop. (O(n) vs. N * log(M) )
    • use sorted_unique if the inputs are already sorted.
  • Use library facilities (e.g. views::zip) to benefit from concept-based optimizations.


4)

compiler flag
-Xclang -verify used for static_asserts
e.g.
clang++ -Xclang -verify -fsyntax-only test_integer_only.cpp

#include <type_traits>

template <typename T>
void strict_int_check() {
    static_assert(std::is_integral<T>::value, "Type must be an integer!");
}

void test() {
    // This line is valid, so no comment needed.
    strict_int_check<int>();

    // We WANT this line to fail. 
    // Without -verify, this breaks the build.
    // With -verify, Clang checks if the error matches the regex in {{...}}.
    strict_int_check<double>(); // expected-error {{Type must be an integer!}}
}

Dec 7, 2025

[C++][Data structure] concurrent skip list.

Here SkipListNode initialize the size to size of SkipListNode + hight of the skiplist node.
https://github.com/facebook/folly/blob/d2e6fe65dfd6b30a9d504d0409ac733cbaa73125/folly/ConcurrentSkipList-inl.h#L66

size_t size =
	sizeof(SkipListNode) + height * sizeof(std::atomic<SkipListNode*>);

This is the clever trick used in C, while SkipListNode has the last data member declared of size 0 array. i.e. if the hight of the SkipListNode is 5, the size of SkipListNode is
SkipListNode + 5 * sizeof(std::atomic),
thus we could access skip_[4] without out-of-idx-bound.
std::atomic<SkipListNode*> skip_[0];
https://github.com/facebook/folly/blob/d2e6fe65dfd6b30a9d504d0409ac733cbaa73125/folly/ConcurrentSkipList-inl.h#L173

Hense std::atomic skip_[0] is malloc not through constructor, when SkipListNode is destructed, should call `skip_[i].~atomic()` manually. (i.e. destruct atomic before its memory being deallocated.)
~SkipListNode() {
	for (uint8_t i = 0; i < height_; ++i) {
      skip_[i].~atomic();
    }
}

Dec 1, 2024

[C++][cpponsea 2024] C++ Cache Friendly Data + Functional + Ranges summary

Reference:
https://www.youtube.com/watch?v=XJzs4kC9d-Y
https://github.com/rollbear/columnist

https://godbolt.org/z/a8P7oTjoh

#include <functional>
#include <iostream>
#include <tuple>
#include <vector>

template<typename... Ts>
class Table {
 public:
  using row = std::tuple<Ts&...>;
  row operator[](size_t i) {
    auto access = [&]<size_t... Is>(std::index_sequence<Is...>) {
      return row{std::get<Is>(data_)[i]...};
    };
    return std::invoke(access, indexes);
  }

  Table() {
    init(indexes);
  }

 private:
  static constexpr std::index_sequence_for<Ts...> indexes{};
  std::tuple<std::vector<Ts>...> data_;

 private:
  template<size_t... I>
  constexpr void init(std::index_sequence<I...>) {
    ((std::get<I>(data_).push_back({42}),...));
  }
};

struct Data1 {
 int value;
};

struct Data2 {
 int value;
};

int main() {

  Table<Data1, Data2> table;
  auto row = table[0];
  std::cout << std::get<0>(row).value << '\n'; // print 42
};


Iterator

Use sentinal pattern.
struct sentinel {}; // or using sentinal = void;

struct iterator {
  using value_type = row;
  using difference_type = ssize_t;

  value_type operator*() const {
    return std::invoke([&]<size_t... Is>(std::index_sequence<Is...>) {
      return value_type{std::get<Is>(t->data_)[offset]...};
    }, t->indexes);
  }

  iterator& operator++() { ++offset; return *this;}
  iterator operator++(int) { auto copy = *this; ++*this; return copy;}
  bool operator==(const iterator&) const = default;
  bool operator==(sentinel) const { return offset == t->size(); }
  table* t;
  size_t offset;
};

Plug in
template<typename... Ts>
class Table {
 public:
  friend class iterator;
  iterator begin() { return {this, 0}; }
  sentinel end() { return {}; }
...
};

Reference:
https://en.cppreference.com/w/cpp/utility/integer_sequence
template<typename...>
struct Table;

template<typename, typename>
struct Row;


template <typename... Ts, size_t... Cs>
struct Row<Table<Ts...>, std::index_sequence<Cs...>> {
  using row_id = typename Table<Ts...>::row_id;

  // Indirection to make std::index_sequence<0, 2, 4> -> I==1 means std::get<2>(...)
  template<size_t I>
  friend auto& get(const Row& r) {
    static constexpr std::array columns{Cs...};
    return std::get<columns[I]>(r.t->data_)[r.offset];
  }

  ...
  Table<Ts...>* t;
  size_t offset;
};


template<typename Table, size_t... Cs>
struct std::tuple_size<Row<Table, std::index_sequence<Cs...>>>
 : std::integral_constant<size_t, sizeof...(Cs)> {};


template <size_t I, typename... Ts, size_t... Cs>
struct std::tuple_element<I, Row<Table<Ts...>, std::index_sequence<Cs...>>> {
  static constexpr std::array indexes = { Cs... };
  using type = Ts...[indexes[I]]&;
};

Select:
template<size_t... Is, typename Table, size_t... Cs>
auto select(const Row<Table, std::index_sequence<Cs...>>& r) {
  static constexpr size_t columns[] { Cs... };
  return Row<Table, std::index_sequence<columns[Is]...>>(r);
}

Usage:
drop_if(values, [](auto r){ auto [x,z] = select<0, 2>(r); return x < z; });
template<typename R, size_t... Cs>
struct range_selector {
  using r_iterator = decltype(std::declval<R&>().begin());
  struct iterator : r_iterator {
    using difference_type = ssize_t;
    using value_type = decltype(select<Cs...>(*std::declval<r_iterator>()));
    
    iterator(const r_iterator& i) : r_iterator(i) {}
    auto operator*() const {
      const r_iterator& i = *this;
      return select<Cs...>(*i);
    }
  };

  iterator begin() { return iterator{ r.begin() }; }
  auto end() { return r.end(); }

  R& r;
};
template<size_t... Cs>
struct range_selector_maker {
  template<typename R>
  friend range_selector<R, Cs...> operator|(R& r, range_selector_maker) {
    return { r };
  }
};

template<size_t... Cs>
range_selector_maker<Cs...> select() { return {}; }

Usage:
for (auto [x, d] : values | select<0, 3>()) {
  std::println("d={} x={}", d, x);
}

Concepts:
template<typename>
inline constexpr bool row_type_v = false;

template<typename T, typename Cs>
inline constexpr bool row_type_v<Row<T, Cs>> = true;

template<typename T>
concept row_type = row_type_v<T>;

Select:
template<size_t... Cs, typename F>
auto select(F&& f) 
  requires (! row_type<std::remove_cvref_t<F>>)
{
  return [f = std::forward<F>(f)]<typename T, typename Is>(row<T, Is> r) {
    return f(select<Cs...>(r));
  };

}
template<typename F>
auto apply(F&& f) {
  return [f = std::forward<F>(f)]<row_type R>(R r) {
    return std::invoke([&]<size_t... Cs>(std::index_sequence<Cs...>) {
      return f(get<Cs>(r)...);
    }, std::make_index_sequence<std::tuple_size_v<R>>{});
  };
}


Usage:
drop_if(values, select<0, 2>(apply([](auto x, auto z) { return x < z; })));

or just:
drop_if(values, select<0, 2>(apply(std::less{})));

Oct 24, 2021

[C++][data structure] intrusive container

Reference:
https://www.boost.org/doc/libs/1_76_0/doc/html/intrusive/intrusive_vs_nontrusive.html

The main difference between intrusive containers and non-intrusive containers is that in C++ non-intrusive containers store copies of values passed by the user. Containers use the Allocator template parameter to allocate the stored values.

On the other hand, an intrusive container does not store copies of passed objects, but it stores the objects themselves.

The additional data needed to insert the object in the container must be provided by the object itself.

For example, to insert MyClass in an intrusive container that implements a linked list, MyClass must contain the needed next and previous pointers.




Jul 7, 2019

[data structure] Advanced Data Structures - 7

Reference:
Memory Hierarchy Models: https://www.youtube.com/watch?v=V3omVLzI0WE
TLPI: http://man7.org/tlpi/

When design data structure, targeting the cache level.


External memory model

(Consider only last 2 level: cache -> disk)
(cell probes, words read from memory)/B <= Memory transfers <= RAM running time

1. Sequential scanning.
O([N/B), i.e ceiling N over B.
B is the word size.
N is the data number.



2. Search trees. B-tree (B+1 as branch factor, B as B number of blocks)
O((B+1)logN) optimized i.e consider binary tree, which is O(2logN)
Omega((B+1)logN) search in comparison model.
Proof:
Take the ratio.




3. Sorting.
O(N/B * n/BlogN/B),i.e read as block B.



4. Permuting
O(min{N, N/B * n/BlogN/B})


5. Buffer-tree.
O(1/B * n/BlogN/B)
For delayed query and batched updates.



tbd

Nov 14, 2018

[Cppcon 2016] High Performance Code 201: Hybrid Data Structures - Chandler Carruth


std::vector's problem, no SSO(small size optimization)
Why? Because STD says when move a vector, it's iterator can't be invalidated.
That implies std::vector's iterator as pointer points to heap memory.
However, SSO vector when moves, it copies, and invalidates the iterators.

Domain specific data structure has it's purpose of efficiency.
(Less corner cases, easier to design.)

Besides domain specific data structure,
why not just using customized allocator with std::vector?

Thus SSO for vector becomes:
template<typename T, int N>
using SmallVector = std::vector<T, short_alloc<T, N>>;

void fun(){
    SmallVector<int, 4>::allocator_type::arena_type a;
    SmallVector<int> v{a};
}

But...
It doesn't work well with interface boundary,
i.e  due to std::vector has allocator as type argument.
void jump(SmallVector<int, 4> &v);

void fun(){
    // Taking short_alloc<int, 8>
    SmallVector<int, 8>::allocator_type::arena_type a;
    SmallVector<int> v{a};
    jump(v);  // doesn't work... callee taking short_alloc<int, 4>
}

Another issue, callee's return type could reference to memory on callee's stack..
i.e
SmallVector<int, 4> fun(){
    SmallVector<int, 4>::allocator_type::arena_type a;
    SmallVector<int> v{a};
    return v; // BAD
}

All of all, the SmallVector loses it's value semantics.
Which is IMPORTANT.

With Domain Specific Type, these issues solved.
SmallVector type in Clang:
template <typename T, unsigned N>
class SmallVector : public SmallVectorImpl<T> {
  typedef typename SmallVectorImpl<T>::U U; // expected-error {{no type named 'U' in 'SmallVectorImpl<CallSite>'}}
  enum {

    MinUs = (static_cast<unsigned int>(sizeof(T))*N + // expected-error {{invalid application of 'sizeof' to an incomplete type 'CallSite'}}
             static_cast<unsigned int>(sizeof(U)) - 1) /
            static_cast<unsigned int>(sizeof(U)),
    NumInlineEltsElts = MinUs
  };
  U InlineElts[NumInlineEltsElts];
public:
  SmallVector() : SmallVectorImpl<T>(NumInlineEltsElts) {
  }

};

Small-size optimization is best when the values are small.
(in C++, copy by value is the default mechanism, although not being well/widely known...)

Design:
  1. Give large objects address identity.
    i.e Use object's memory address as identity avoids object's content equality test.
  2. SmallVector<std::unique_ptr<BigObject>, 4> Objects;
    
    BumpPtrAllocator impl, purpose, make BigObject as compact as possible on heap memory.
    // FAST
    class BumpPtrAllocator {
        constexpr int SlabSize = 4096;
        SmallVector<void *, 4> Slabs;
        void *CurPtr, *End;
    
    public:
        void *Allocate(int Size) P
            if (Size >= (End - CurPtr)) {
                CurPtr = malloc(SlabSize);
                End = CurPtr + SlabSize;
                Slabs.push_back(CurPtr);
            }
    
            void *Ptr = CurPtr;
            CurPtr += Size;
            return Ptr;
        }
        // ...
    };
    
  3. If pointers are too large, use an index.
  4. Aggressively pack the bits.
    PointerIntPair:
    http://llvm.org/doxygen/classllvm_1_1PointerIntPair.html
    PointerEmbeddedInt:
    http://llvm.org/doxygen/classllvm_1_1PointerEmbeddedInt.html
    TinyPtrVector:
    http://llvm.org/doxygen/classllvm_1_1TinyPtrVector.html
    Thus, we have SmallMutiMap:
  5. template<typename KeyT, typename ValueT>
    using SmallMultiMap = SmallDenseMap<KeyT, TinyPtrVector<ValueT>>;
    
  6. Use bitfields everywhere.
  7. Sometimes, we need an ordering.
    i.e comparison operator.
  8. Where possible, sort the vector.
    i.e gives you a linear BST, works well with CPU pre-fetching.
  9. What if there's no intrinsic ordering?
    We have SmallSetVector:
    (Has a set, has a vector, when insert, check data in set, and insert into vector.)
    http://llvm.org/doxygen/classllvm_1_1SmallSetVector.html

Jul 4, 2018

[algorithm][data structure] KD Tree

[algorithm][data structure] Quad Tree

// C++ Implementation of Quad Tree
#include <iostream>
#include <cmath>
using namespace std;
 
// Used to hold details of a point
struct Point
{
    int x;
    int y;
    Point(int _x, int _y)
    {
        x = _x;
        y = _y;
    }
    Point()
    {
        x = 0;
        y = 0;
    }
};
 
// The objects that we want stored in the quadtree
struct Node
{
    Point pos;
    int data;
    Node(Point _pos, int _data)
    {
        pos = _pos;
        data = _data;
    }
    Node()
    {
        data = 0;
    }
};
 
// The main quadtree class
class Quad
{
    // Hold details of the boundary of this node
    Point topLeft;
    Point botRight;
 
    // Contains details of node
    Node *n;
 
    // Children of this tree
    Quad *topLeftTree;
    Quad *topRightTree;
    Quad *botLeftTree;
    Quad *botRightTree;
 
public:
    Quad()
    {
        topLeft = Point(0, 0);
        botRight = Point(0, 0);
        n = NULL;
        topLeftTree  = NULL;
        topRightTree = NULL;
        botLeftTree  = NULL;
        botRightTree = NULL;
    }
    Quad(Point topL, Point botR)
    {
        n = NULL;
        topLeftTree  = NULL;
        topRightTree = NULL;
        botLeftTree  = NULL;
        botRightTree = NULL;
        topLeft = topL;
        botRight = botR;
    }
    void insert(Node*);
    Node* search(Point);
    bool inBoundary(Point);
};
 
// Insert a node into the quadtree
void Quad::insert(Node *node)
{
    if (node == NULL)
        return;
 
    // Current quad cannot contain it
    if (!inBoundary(node->pos))
        return;
 
    // We are at a quad of unit area
    // We cannot subdivide this quad further
    if (abs(topLeft.x - botRight.x) <= 1 &&
        abs(topLeft.y - botRight.y) <= 1)
    {
        if (n == NULL)
            n = node;
        return;
    }
 
    if ((topLeft.x + botRight.x) / 2 >= node->pos.x)
    {
        // Indicates topLeftTree
        if ((topLeft.y + botRight.y) / 2 >= node->pos.y)
        {
            if (topLeftTree == NULL)
                topLeftTree = new Quad(
                    Point(topLeft.x, topLeft.y),
                    Point((topLeft.x + botRight.x) / 2,
                        (topLeft.y + botRight.y) / 2));
            topLeftTree->insert(node);
        }
 
        // Indicates botLeftTree
        else
        {
            if (botLeftTree == NULL)
                botLeftTree = new Quad(
                    Point(topLeft.x,
                        (topLeft.y + botRight.y) / 2),
                    Point((topLeft.x + botRight.x) / 2,
                        botRight.y));
            botLeftTree->insert(node);
        }
    }
    else
    {
        // Indicates topRightTree
        if ((topLeft.y + botRight.y) / 2 >= node->pos.y)
        {
            if (topRightTree == NULL)
                topRightTree = new Quad(
                    Point((topLeft.x + botRight.x) / 2,
                        topLeft.y),
                    Point(botRight.x,
                        (topLeft.y + botRight.y) / 2));
            topRightTree->insert(node);
        }
 
        // Indicates botRightTree
        else
        {
            if (botRightTree == NULL)
                botRightTree = new Quad(
                    Point((topLeft.x + botRight.x) / 2,
                        (topLeft.y + botRight.y) / 2),
                    Point(botRight.x, botRight.y));
            botRightTree->insert(node);
        }
    }
}
 
// Find a node in a quadtree
Node* Quad::search(Point p)
{
    // Current quad cannot contain it
    if (!inBoundary(p))
        return NULL;
 
    // We are at a quad of unit length
    // We cannot subdivide this quad further
    if (n != NULL)
        return n;
 
    if ((topLeft.x + botRight.x) / 2 >= p.x)
    {
        // Indicates topLeftTree
        if ((topLeft.y + botRight.y) / 2 >= p.y)
        {
            if (topLeftTree == NULL)
                return NULL;
            return topLeftTree->search(p);
        }
 
        // Indicates botLeftTree
        else
        {
            if (botLeftTree == NULL)
                return NULL;
            return botLeftTree->search(p);
        }
    }
    else
    {
        // Indicates topRightTree
        if ((topLeft.y + botRight.y) / 2 >= p.y)
        {
            if (topRightTree == NULL)
                return NULL;
            return topRightTree->search(p);
        }
 
        // Indicates botRightTree
        else
        {
            if (botRightTree == NULL)
                return NULL;
            return botRightTree->search(p);
        }
    }
};
 
// Check if current quadtree contains the point
bool Quad::inBoundary(Point p)
{
    return (p.x >= topLeft.x &&
        p.x <= botRight.x &&
        p.y >= topLeft.y &&
        p.y <= botRight.y);
}
 
// Driver program
int main()
{
    Quad center(Point(0, 0), Point(8, 8));
    Node a(Point(1, 1), 1);
    Node b(Point(2, 5), 2);
    Node c(Point(7, 6), 3);
    center.insert(&a);
    center.insert(&b);
    center.insert(&c);
    cout << "Node a: " <<
        center.search(Point(1, 1))->data << "\n";
    cout << "Node b: " <<
        center.search(Point(2, 5))->data << "\n";
    cout << "Node c: " <<
        center.search(Point(7, 6))->data << "\n";
    cout << "Non-existing node: "
        << center.search(Point(5, 5));
    return 0;
}

Oct 3, 2016

[cppcon2016] extern "C": Talking to C Programmers About C++

extern "C": Talking to C Programmers About C++
https://goo.gl/V4wJG3
www.dansaks.com


What’s a Data Type?
A data type is a bundle of compile-time properties for an object:
• size and alignment
• set of valid values
• set of permitted operations

“If you’re arguing, you’re losing.” 

Sep 30, 2016

[cppcon2016][c++] Leak-Freedom in C++ - note

CppCon 2016 - Herb Sutter “Leak-Freedom in C++... By Default.”-
https://goo.gl/2TNgQI
--
  • Ensure an object will be destroyed once it is no longer needed.
  • Correct by construction!
template<typename T>
using Pimpl = const unique_ptr<T>;
unique_ptr<data[]> ptr;


Double linked list:
  • a unique_ptr to the next
  • a raw ptr to the back
shared_ptr with alias constructor:
  • Do not violate layering.
  • Don't create ownership cycles across modules by owning 'upward' (violates layering)
  • Use weak_ptr to break cycles.

How?
  • Don't pass an owner down to 'unknow code' that might store it.
    e.g storing a shared_ptr
  • Simple.
    Use weak_ptr inside the call back callable object which point
    to outside resource.
ownership types:
  • 1 object, 1 owner:
    unique_ptr
  • 1 object , n owners:
    shared_ptr
  • N objects, 1 or n owners:
    deffered_ptr
Reachability is a property of the while group.
Not detectable from 1 object, or subgroup.

Idea:
heap for deffered_ptr is isolated.
Each module could have one isolated heap.
github.com/hsutter/gcpp