### Manual Setup: Registering Custom Tree Types with X-Macros Source: https://github.com/z-libs/ztree.h/blob/main/README.md Shows how to manually set up custom tree types in a separate header file using X-Macros. This involves defining a comparison function and then using the REGISTER_ZTREE_TYPES macro to declare the key-value types and their associated comparison function before including ztree.h. ```c #ifndef MY_TREES_H #define MY_TREES_H // Comparator must match: int (*)(const Key*, const Key*). int my_int_cmp(const int* a, const int* b); #define REGISTER_ZTREE_TYPES(X) \ X(int, float, MyMap, my_int_cmp) // **IT HAS TO BE INCLUDED AFTER, NOT BEFORE**. #include "ztree.h" #endif ``` -------------------------------- ### Initialize Empty Tree (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Shows the initialization of an empty ztree. The `ztree_init` function is called with the registered type name to create a tree structure ready for operations. The example verifies the initial size and checks if the root is NULL. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { // Initialize an empty tree ztree_Int t = ztree_init(Int); printf("Initial size: %zu\n", t.size); printf("Root is NULL: %s\n", t.root == NULL ? "yes" : "no"); // Output: Initial size: 0 // Output: Root is NULL: yes return 0; } ``` -------------------------------- ### Get Minimum and Maximum Nodes using ztree_min/ztree_max (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Illustrates how to retrieve the nodes with the minimum and maximum keys from a ztree. Returns NULL if the tree is empty. Requires a comparison function for the key type. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); // Insert in mixed order int keys[] = {20, 10, 30, 5, 15, 25, 35}; for (int i = 0; i < 7; ++i) { ztree_insert(&t, keys[i], keys[i] * 10); } ztree_node_Int *min_node = ztree_min(&t); ztree_node_Int *max_node = ztree_max(&t); printf("Minimum: key=%d, value=%d\n", min_node->key, min_node->value); printf("Maximum: key=%d, value=%d\n", max_node->key, max_node->value); // Output: Minimum: key=5, value=50 // Output: Maximum: key=35, value=350 ztree_clear(&t); return 0; } ``` -------------------------------- ### Find Node by Key (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates how to find a node in the ztree using its key. The `ztree_find` function returns a pointer to the node if found, or `NULL` otherwise. The example shows finding both an existing and a non-existing key in a symbol table. ```c #include #include static int str_cmp(const char **a, const char **b) { return strcmp(*a, *b); } #define REGISTER_ZTREE_TYPES(X) \ X(const char*, int, SymbolTable, str_cmp) #include "ztree.h" int main(void) { ztree_SymbolTable symbols = ztree_init(SymbolTable); ztree_insert(&symbols, "count", 1); ztree_insert(&symbols, "velocity", 2); ztree_insert(&symbols, "buffer", 3); // Find existing key ztree_node_SymbolTable *node = ztree_find(&symbols, "velocity"); if (node) { printf("Found '%s' with value: %d\n", node->key, node->value); // Output: Found 'velocity' with value: 2 } // Find non-existing key node = ztree_find(&symbols, "unknown"); printf("Unknown key result: %s\n", node == NULL ? "NULL" : "found"); // Output: Unknown key result: NULL ztree_clear(&symbols); return 0; } ``` -------------------------------- ### Insert Key-Value Pairs and Update (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Illustrates inserting key-value pairs into a ztree and updating the value for an existing key. The `ztree_insert` function returns `Z_OK` on success. The example also demonstrates finding a node after an update using `ztree_find`. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); // Insert new entries int result = ztree_insert(&t, 10, 100); printf("Insert result: %d (Z_OK=%d)\n", result, Z_OK); // Output: Insert result: 0 (Z_OK=0) ztree_insert(&t, 5, 50); ztree_insert(&t, 20, 200); printf("Size after inserts: %zu\n", t.size); // Output: Size after inserts: 3 // Update existing key ztree_insert(&t, 10, 999); ztree_node_Int *n = ztree_find(&t, 10); printf("Updated value for key 10: %d\n", n->value); // Output: Updated value for key 10: 999 ztree_clear(&t); return 0; } ``` -------------------------------- ### C Usage: Define and Use Type-Safe Red-Black Tree Source: https://github.com/z-libs/ztree.h/blob/main/README.md Demonstrates how to define and use a type-safe Red-Black Tree in C using ztree.h. It involves defining a comparison function and registering the key-value types via X-Macros. The example shows insertion, finding, and iterating through the tree. ```c #include #include // Define comparison function: int (*)(const Key*, const Key*) // Returns <0 if a < b, 0 if equal, >0 if a > b. static int str_cmp(const char** a, const char** b) { return strcmp(*a, *b); } // Register types: X(KeyType, ValueType, Name, CompareFunc) #define REGISTER_ZTREE_TYPES(X) \ X(const char*, int, SymbolTable, str_cmp) #include "ztree.h" int main(void) { // Initialize. ztree_SymbolTable symbols = ztree_init(SymbolTable); // Insert. ztree_insert(&symbols, "velocity", 100); ztree_insert(&symbols, "gravity", 9); // Find. ztree_node_SymbolTable* node = ztree_find(&symbols, "velocity"); if (node) { printf("Velocity is: %d\n", node->value); } // Iteration (sorted). ztree_foreach(&symbols, it) { printf("%s: %d\n", it->key, it->value); } // Cleanup. ztree_free(&symbols); // (mapped via ztree_free) return 0; } ``` -------------------------------- ### C++ Usage: Use Type-Safe Map with RAII and Iterators Source: https://github.com/z-libs/ztree.h/blob/main/README.md Illustrates using ztree.h as a C++ map with RAII, iterators, and a std::map-like API. It supports C++ objects like std::string and uses new/delete internally for proper constructor/destructor calls. The example shows insertion, iteration, and lower_bound. ```cpp #include #include // Comparator for int keys (descending order). static int int_cmp(const int* a, const int* b) { return *b - *a; } // Register C backend. #define REGISTER_ZTREE_TYPES(X) \ X(int, std::string, Leaderboard, int_cmp) #include "ztree.h" int main() { // RAII handles memory automatically. z_tree::map board; // Operator[] support. board[100] = "Alice"; board[50] = "Bob"; // Range-based for loops (via proxy object). for(auto entry : board) { std::cout << entry.value() << ": " << entry.key() << "\n"; } // Lower bound. auto it = board.lower_bound(80); if (it != board.end()) { std::cout << "Top score <= 80 is: " << it.value() << "\n"; } return 0; } ``` -------------------------------- ### ztree Manual Navigation: Next and Previous Nodes Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates how to retrieve the successor (next) or predecessor (previous) node in sorted order within a ztree. Returns NULL when the end of the tree is reached. Requires the ztree header and a comparison function. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); ztree_insert(&t, 10, 100); ztree_insert(&t, 20, 200); ztree_insert(&t, 30, 300); // Navigate forward from min printf("Forward from min:\n"); for (ztree_node_Int *n = ztree_min(&t); n != NULL; n = ztree_next(n)) { printf(" %d\n", n->key); } // Output: Forward from min: // Output: 10 // Output: 20 // Output: 30 // Navigate backward from max printf("Backward from max:\n"); for (ztree_node_Int *n = ztree_max(&t); n != NULL; n = ztree_prev(n)) { printf(" %d\n", n->key); } // Output: Backward from max: // Output: 30 // Output: 20 // Output: 10 ztree_clear(&t); return 0; } ``` -------------------------------- ### C API - Initialization & Management Source: https://github.com/z-libs/ztree.h/blob/main/README.md Functions for initializing, clearing, and managing tree structures in C. ```APIDOC ## C API - Initialization & Management ### Description Functions for initializing, clearing, and managing tree structures in C. ### Macros #### `ztree_init(Name)` - **Description**: Returns an empty tree structure initialized to zero. #### `ztree_clear(t)` - **Description**: Frees all nodes in the tree and resets size to 0. - **Parameters**: - `t` (ztree_t*) - Pointer to the tree to clear. #### `ztree_autofree(Name)` - **Description**: Declares a tree that automatically calls clear when the variable leaves scope (RAII style, GCC/Clang only). - **Note**: This macro is specific to GCC/Clang compilers. ``` -------------------------------- ### ztree.h C API Initialization and Management Source: https://github.com/z-libs/ztree.h/blob/main/README.md Macros for initializing, clearing, and managing ztree structures in C. `ztree_init` creates a new tree, `ztree_clear` frees its nodes, and `ztree_autofree` enables RAII-style automatic cleanup (GCC/Clang only). ```c #define ztree_init(Name) ... #define ztree_clear(t) ... #define ztree_autofree(Name) ... ``` -------------------------------- ### Short Names (Opt-In) Source: https://github.com/z-libs/ztree.h/blob/main/README.md Enabling shorter, more convenient macro names for the ztree API. ```APIDOC ## Short Names (Opt-In) ### Description If you prefer a cleaner API and do not have naming conflicts with other libraries, you can define `ZTREE_SHORT_NAMES` before including the `ztree.h` header. This enables shorter, more convenient macro names. ### Usage Define `ZTREE_SHORT_NAMES` before including the header: ```c #define ZTREE_SHORT_NAMES #include "ztree.h" // Now you can use shorter names: ztree_SymbolTable t = tree_init(SymbolTable); // Instead of ztree_init tree_insert(&t, k, v); // Instead of ztree_insert tree_foreach(&t, it) { ... } // Instead of ztree_foreach ``` **Note**: This option is purely for convenience and does not change the underlying functionality of the API. ``` -------------------------------- ### Range Query with ztree_lower_bound (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Shows how to use ztree_lower_bound to find the first node with a key greater than or equal to a given key. This is useful for range queries and finding closest matches. Returns NULL if no such element exists. Requires a custom comparison function for string keys. ```c #include #include static int str_cmp(const char **a, const char **b) { return strcmp(*a, *b); } #define REGISTER_ZTREE_TYPES(X) \ X(const char*, int, SymbolTable, str_cmp) #include "ztree.h" int main(void) { ztree_SymbolTable symbols = ztree_init(SymbolTable); ztree_insert(&symbols, "alpha", 1); ztree_insert(&symbols, "buffer", 2); ztree_insert(&symbols, "beta", 3); ztree_insert(&symbols, "count", 4); // Find lower bound for "b" - first key >= "b" const char *search = "b"; ztree_node_SymbolTable *lb = ztree_lower_bound(&symbols, search); if (lb) { printf("Lower bound for '%s': '%s'\n", search, lb->key); // Output: Lower bound for 'b': 'beta' // Iterate from lower bound to find all "b*" matches printf("Matching candidates:\n"); for (ztree_node_SymbolTable *n = lb; n != NULL; n = ztree_next(n)) { if (n->key[0] != 'b') break; printf(" -> %s\n", n->key); } // Output: -> beta // Output: -> buffer } ztree_clear(&symbols); return 0; } ``` -------------------------------- ### Register Types and Initialize Tree (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates how to register custom types using X-Macros and initialize an empty ztree. The `REGISTER_ZTREE_TYPES` macro is used to define the key type, value type, a name for the tree, and a comparison function. The `ztree_init` function creates a new tree instance. ```c #include // Comparison function: int (*)(const Key*, const Key*) int int_cmp(const int *a, const int *b) { return (*a > *b) - (*a < *b); } // Register types: X(KeyType, ValueType, Name, CompareFunc) #define REGISTER_ZTREE_TYPES(X) \ X(int, int, IntMap, int_cmp) #include "ztree.h" int main(void) { ztree_IntMap tree = ztree_init(IntMap); ztree_insert(&tree, 10, 100); ztree_insert(&tree, 5, 50); ztree_insert(&tree, 20, 200); printf("Tree size: %zu\n", tree.size); // Output: Tree size: 3 ztree_clear(&tree); return 0; } ``` -------------------------------- ### C++ z_tree::map Iterators: STL-Compatible Navigation Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates the STL-compatible bidirectional iterators provided by the C++ `z_tree::map` wrapper. Supports `begin()`, `end()`, pre/post-increment (`++`), and pre/post-decrement (`--`) for navigation. Requires `` and the ztree header. ```cpp #include static int int_cmp(const int* a, const int* b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, IntInt, int_cmp) #include "ztree.h" int main() { z_tree::map m; m[10] = 100; m[20] = 200; m[30] = 300; // Forward iteration std::cout << "Forward iteration:" << std::endl; for (auto it = m.begin(); it != m.end(); ++it) { std::cout << " " << it.key() << " -> " << it.value() << std::endl; } // Output: Forward iteration: // Output: 10 -> 100 // Output: 20 -> 200 // Output: 30 -> 300 // Bidirectional - start from end and go backward std::cout << "Backward from end:" << std::endl; auto it = m.end(); while (it != m.begin()) { --it; std::cout << " " << it.key() << " -> " << it.value() << std::endl; } // Output: Backward from end: // Output: 30 -> 300 // Output: 20 -> 200 // Output: 10 -> 100 // Arrow operator accesses value directly it = m.begin(); std::cout << "First value via ->: " << *it-> << std::endl; return 0; } ``` -------------------------------- ### C API - Iteration Source: https://github.com/z-libs/ztree.h/blob/main/README.md Macros for iterating through the elements of the C tree structure. ```APIDOC ## C API - Iteration ### Description Macros for iterating through the elements of the C tree structure. ### Macros #### `ztree_next(node)` - **Description**: Returns the successor node (in sorted order). - **Parameters**: - `node` (const ztree_node_t*) - Pointer to the current node. - **Returns**: Pointer to the next node, or `NULL` if it's the last node. #### `ztree_prev(node)` - **Description**: Returns the predecessor node. - **Parameters**: - `node` (const ztree_node_t*) - Pointer to the current node. - **Returns**: Pointer to the previous node, or `NULL` if it's the first node. #### `ztree_foreach(t, it)` - **Description**: Standard traversal of the tree. - **Parameters**: - `t` (const ztree_t*) - Pointer to the tree. - `it` - Variable to hold the current node pointer during iteration. - **Usage**: `ztree_foreach(my_tree, node) { /* use node */ }` #### `ztree_foreach_safe(t, it, safe)` - **Description**: Traversal that allows `ztree_remove` on the current iterator. - **Parameters**: - `t` (ztree_t*) - Pointer to the tree. - `it` - Variable to hold the current node pointer during iteration. - `safe` - Variable to hold a safe copy of the iterator for removal. - **Usage**: `ztree_foreach_safe(my_tree, node, safe_node) { ztree_remove(my_tree, node->key); }` #### `ztree_foreach_reverse(t, it)` - **Description**: Standard reverse traversal of the tree. - **Parameters**: - `t` (const ztree_t*) - Pointer to the tree. - `it` - Variable to hold the current node pointer during iteration. - **Usage**: `ztree_foreach_reverse(my_tree, node) { /* use node */ }` ``` -------------------------------- ### ztree.h Short Names Opt-In Source: https://github.com/z-libs/ztree.h/blob/main/README.md Enables a shorter, more convenient API for ztree.h by defining the `ZTREE_SHORT_NAMES` macro before including the header. This renames functions and macros to be more concise, reducing potential naming conflicts. ```c #define ZTREE_SHORT_NAMES #include "ztree.h" // Example usage: // ztree_SymbolTable t = tree_init(SymbolTable); // tree_insert(&t, k, v); // tree_foreach(&t, it) { ... } ``` -------------------------------- ### ztree.h C API Iteration Source: https://github.com/z-libs/ztree.h/blob/main/README.md Macros for iterating through ztree structures in C. `ztree_next` and `ztree_prev` navigate to successor/predecessor nodes. `ztree_foreach` provides standard traversal, `ztree_foreach_safe` allows safe removal during iteration, and `ztree_foreach_reverse` enables reverse traversal. ```c #define ztree_next(node) ... #define ztree_prev(node) ... #define ztree_foreach(t, it) ... #define ztree_foreach_safe(t, it, safe) ... #define ztree_foreach_reverse(t, it) ... ``` -------------------------------- ### ztree.h C API Data Access Source: https://github.com/z-libs/ztree.h/blob/main/README.md Macros for accessing data within ztree structures in C. `ztree_find` searches for a key, `ztree_lower_bound` finds the first element not less than a key, and `ztree_min`/`ztree_max` return the minimum/maximum keyed nodes. ```c #define ztree_find(t, key) ... #define ztree_lower_bound(t, key) ... #define ztree_min(t) ... #define ztree_max(t) ... ``` -------------------------------- ### Memory Management Override Source: https://github.com/z-libs/ztree.h/blob/main/README.md How to override the default memory allocation functions (`malloc`/`free` or `new`/`delete`) for ztree. ```APIDOC ## Memory Management Override ### Description By default, `ztree.h` uses standard C library functions (`malloc`, `free`) in C mode and `new`/`delete` in C++ mode. This section explains how to override these defaults, for example, to use custom allocators like C arenas. ### Global Override To use a custom allocator, define the `Z_MALLOC` and `Z_FREE` macros *before* including `ztree.h`. It's recommended to do this within a custom registry header. ### Example ```c #ifndef MY_TREES_H #define MY_TREES_H #include "my_memory.h" // Assume this header defines my_alloc and my_free // Override global allocators #define Z_MALLOC(sz) my_alloc(sz) #define Z_FREE(p) my_free(p) // (ztree doesn't use realloc/calloc, but defining them keeps consistency) #include "ztree.h" #endif ``` **Note**: Ensure that your custom allocation functions are compatible with the requirements of `ztree.h`. ``` -------------------------------- ### C++ z_tree::map: RAII Wrapper for Tree Map Source: https://context7.com/z-libs/ztree.h/llms.txt Illustrates the C++ `z_tree::map` wrapper, which provides automatic memory management (RAII), STL-style iterators, and `operator[]` access. Memory is automatically deallocated when the map object goes out of scope. Requires ``, ``, and the ztree header. ```cpp #include #include static int int_cmp(const int* a, const int* b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, std::string, StringMap, int_cmp) #include "ztree.h" int main() { // RAII - memory automatically managed z_tree::map m; // Insert with insert() method m.insert(10, "ten"); m.insert(5, "five"); // Insert with operator[] m[20] = "twenty"; m[15] = "fifteen"; std::cout << "Size: " << m.size() << std::endl; std::cout << "Empty: " << (m.empty() ? "yes" : "no") << std::endl; // Output: Size: 4 // Output: Empty: no // Access with operator[] std::cout << "m[10] = " << m[10] << std::endl; // Output: m[10] = ten // Find returns pointer or nullptr std::string *val = m.find(5); if (val) { std::cout << "Found key 5: " << *val << std::endl; // Output: Found key 5: five } // Range-based for loop (sorted order) std::cout << "All entries:" << std::endl; for (auto entry : m) { std::cout << " " << entry.key() << " -> " << entry.value() << std::endl; } // Output: All entries: // Output: 5 -> five // Output: 10 -> ten // Output: 15 -> fifteen // Output: 20 -> twenty return 0; // Memory automatically freed here } ``` -------------------------------- ### ztree Clear: Freeing All Nodes Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates the use of `ztree_clear` to deallocate all nodes within a ztree, resetting its size to zero. The tree remains usable for subsequent insertions. Requires the ztree header and a comparison function. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); ztree_insert(&t, 1, 10); ztree_insert(&t, 2, 20); ztree_insert(&t, 3, 30); printf("Before clear: size=%zu\n", t.size); // Output: Before clear: size=3 ztree_clear(&t); printf("After clear: size=%zu, root=%s\n", t.size, t.root == NULL ? "NULL" : "exists"); // Output: After clear: size=0, root=NULL // Tree can be reused ztree_insert(&t, 100, 1000); printf("After reuse: size=%zu\n", t.size); // Output: After reuse: size=1 ztree_clear(&t); return 0; } ``` -------------------------------- ### C++ API - `z_tree::map` Class Source: https://github.com/z-libs/ztree.h/blob/main/README.md The C++ wrapper class `z_tree::map` provides RAII and adheres to standard C++ practices. ```APIDOC ## C++ API - `z_tree::map` Class ### Description The C++ wrapper class `z_tree::map` provides RAII and adheres to standard C++ practices, delegating logic to the underlying C implementation. ### Constructors & Management #### `map()` - **Description**: Default constructor, creates an empty map. #### `~map()` - **Description**: Destructor. Automatically frees all nodes and associated memory. #### `operator=` - **Description**: Copy assignment is deleted. Move assignment transfers ownership of resources. #### `clear()` - **Description**: Removes all elements from the map, freeing associated memory. ``` -------------------------------- ### In-Order Iteration with ztree_foreach (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates forward and reverse in-order iteration through all nodes in a ztree. The iterator provides access to `->key` and `->value`. `ztree_foreach_safe` is recommended for safe removal during iteration. Requires a comparison function for the key type. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); // Insert in reverse order for (int i = 5; i >= 1; --i) { ztree_insert(&t, i, i * 100); } // Forward iteration (ascending order) printf("Forward iteration:\n"); ztree_foreach(&t, it) { printf(" key=%d, value=%d\n", it->key, it->value); } // Output: Forward iteration: // Output: key=1, value=100 // Output: key=2, value=200 // Output: key=3, value=300 // Output: key=4, value=400 // Output: key=5, value=500 // Reverse iteration (descending order) printf("Reverse iteration:\n"); ztree_foreach_reverse(&t, rit) { printf(" key=%d, value=%d\n", rit->key, rit->value); } // Output: Reverse iteration: // Output: key=5, value=500 // Output: key=4, value=400 // Output: key=3, value=300 // Output: key=2, value=200 // Output: key=1, value=100 ztree_clear(&t); return 0; } ``` -------------------------------- ### ztree.h C++ Wrapper Class `z_tree::map` Source: https://github.com/z-libs/ztree.h/blob/main/README.md The C++ `z_tree::map` class provides RAII-compliant access to the ztree functionality. It manages memory automatically via constructors and destructors and offers methods for access, iteration, and modification, mirroring the C API. ```cpp namespace z_tree { template class map { public: map(); ~map(); map& operator=(const map&) = delete; map& operator=(map&&) noexcept; void clear(); size_t size() const; bool empty() const; V& operator[](const K& key); const V* find(const K& key) const; // ... other methods }; } ``` -------------------------------- ### Z-Tree Short Names API Source: https://context7.com/z-libs/ztree.h/llms.txt Enables the use of shorter API names by defining ZTREE_SHORT_NAMES before including the ztree header. This removes the 'ztree_' prefix from types and functions, simplifying code. Requires the ztree header and REGISTER_ZTREE_TYPES macro. ```c #include int int_cmp(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, IntMap, int_cmp) #define ZTREE_SHORT_NAMES #include "ztree.h" int main(void) { // Use tree() instead of ztree_ tree(IntMap) t = tree_init(IntMap); // Short function names tree_insert(&t, 10, 100); tree_insert(&t, 5, 50); // Short iteration macro tree_foreach(&t, node) { printf("%d -> %d\n", node->key, node->value); } tree_clear(&t); return 0; } ``` -------------------------------- ### C API - Data Access Source: https://github.com/z-libs/ztree.h/blob/main/README.md Functions for finding and accessing data within the C tree structure. ```APIDOC ## C API - Data Access ### Description Functions for finding and accessing data within the C tree structure. ### Macros #### `ztree_find(t, key)` - **Description**: Returns a pointer to the node matching `key`, or `NULL`. - **Parameters**: - `t` (const ztree_t*) - Pointer to the tree to search. - `key` - The key to search for. - **Returns**: A pointer to the node if found, otherwise `NULL`. #### `ztree_lower_bound(t, key)` - **Description**: Returns a pointer to the first node that is not less than `key` (>=). - **Parameters**: - `t` (const ztree_t*) - Pointer to the tree to search. - `key` - The key to search for. - **Returns**: A pointer to the first node >= `key`, or `NULL` if no such node exists. #### `ztree_min(t)` - **Description**: Returns the node with the minimum key. - **Parameters**: - `t` (const ztree_t*) - Pointer to the tree. - **Returns**: A pointer to the node with the minimum key, or `NULL` if the tree is empty. ``` -------------------------------- ### Remove Node by Key using ztree_remove (C) Source: https://context7.com/z-libs/ztree.h/llms.txt Demonstrates how to remove a node with a specific key from a ztree. The tree automatically rebalances after removal. This function requires a comparison function for the key type. ```c #include int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); ztree_insert(&t, 20, 200); ztree_insert(&t, 10, 100); ztree_insert(&t, 30, 300); ztree_insert(&t, 5, 50); printf("Size before removal: %zu\n", t.size); // Output: Size before removal: 4 // Remove a node ztree_remove(&t, 10); printf("Size after removal: %zu\n", t.size); // Output: Size after removal: 3 // Verify removal printf("Key 10 exists: %s\n", ztree_find(&t, 10) ? "yes" : "no"); printf("Key 5 exists: %s\n", ztree_find(&t, 5) ? "yes" : "no"); // Output: Key 10 exists: no // Output: Key 5 exists: yes ztree_clear(&t); return 0; } ``` -------------------------------- ### Z-Tree Custom Memory Allocators Source: https://context7.com/z-libs/ztree.h/llms.txt Allows integration with custom memory allocators by defining Z_MALLOC and Z_FREE macros before including the ztree header. This is useful for memory pooling or specific allocation strategies. Requires the ztree header and REGISTER_ZTREE_TYPES macro. ```c #include #include // Track allocations for demonstration static int alloc_count = 0; void* my_alloc(size_t sz) { alloc_count++; return malloc(sz); } void my_free(void* p) { alloc_count--; free(p); } // Override allocators BEFORE including ztree.h #define Z_MALLOC(sz) my_alloc(sz) #define Z_FREE(p) my_free(p) int cmp_int(const int *a, const int *b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, Int, cmp_int) #include "ztree.h" int main(void) { ztree_Int t = ztree_init(Int); ztree_insert(&t, 1, 10); ztree_insert(&t, 2, 20); ztree_insert(&t, 3, 30); printf("Active allocations: %d\n", alloc_count); ztree_clear(&t); printf("After clear: %d\n", alloc_count); return 0; } ``` -------------------------------- ### C API - Modification Source: https://github.com/z-libs/ztree.h/blob/main/README.md Functions for inserting and removing elements from the C tree structure. ```APIDOC ## C API - Modification ### Description Functions for inserting and removing elements from the C tree structure. ### Macros #### `ztree_insert(t, key, val)` - **Description**: Inserts a key-value pair. Updates value if key exists. - **Parameters**: - `t` (ztree_t*) - Pointer to the tree. - `key` - The key to insert. - `val` - The value to associate with the key. - **Returns**: `Z_OK` on success, `Z_ENOMEM` if memory allocation fails. #### `ztree_remove(t, key)` - **Description**: Removes the node with `key`. Rebalances the tree automatically. - **Parameters**: - `t` (ztree_t*) - Pointer to the tree. - `key` - The key of the node to remove. ``` -------------------------------- ### C++ API - `z_tree::map` Access & Iterators Source: https://github.com/z-libs/ztree.h/blob/main/README.md Methods for accessing elements and using iterators with the `z_tree::map` class. ```APIDOC ## C++ API - `z_tree::map` Access & Iterators ### Description Methods for accessing elements and using iterators with the `z_tree::map` class. ### Methods #### `size()` - **Description**: Returns the current number of elements in the map. - **Returns**: `size_t` - The number of elements. #### `empty()` - **Description**: Checks if the map is empty. - **Returns**: `bool` - `true` if the map contains no elements, `false` otherwise. #### `operator[](key)` - **Description**: Returns a reference to the value associated with `key`. If `key` does not exist, a new element is inserted with a default-constructed value. - **Parameters**: - `key` - The key to access. - **Returns**: A reference to the value. #### `find(key)` - **Description**: Returns a pointer to the value associated with `key`, or `nullptr` if the key is not found. - **Parameters**: - `key` - The key to search for. - **Returns**: `V*` - Pointer to the value, or `nullptr`. #### `lower_bound(key)` - **Description**: Returns an iterator to the first element whose key is not less than `key` (i.e., greater than or equal to `key`). - **Parameters**: - `key` - The key to search for. - **Returns**: An iterator to the first element >= `key`, or `end()` if no such element exists. #### `begin()`, `end()` - **Description**: Returns bidirectional iterators to the beginning and end of the map, respectively, conforming to standard C++ iterator concepts. ``` -------------------------------- ### ztree.h C API Modification Source: https://github.com/z-libs/ztree.h/blob/main/README.md Macros for modifying ztree structures in C. `ztree_insert` adds or updates a key-value pair, returning `Z_OK` or `Z_ENOMEM`. `ztree_remove` deletes a node by key and rebalances the tree. ```c #define ztree_insert(t, key, val) ... #define ztree_remove(t, key) ... ``` -------------------------------- ### C++ API - `z_tree::map` Modification Source: https://github.com/z-libs/ztree.h/blob/main/README.md Methods for inserting and removing elements from the `z_tree::map` class. ```APIDOC ## C++ API - `z_tree::map` Modification ### Description Methods for inserting and removing elements from the `z_tree::map` class. ### Methods #### `insert(k, v)` - **Description**: Inserts a key-value pair. If the key already exists, its associated value is updated. - **Parameters**: - `k` - The key to insert. - `v` - The value to associate with the key. #### `erase(key)` - **Description**: Removes the element with the specified `key` from the map. - **Parameters**: - `key` - The key of the element to remove. #### `erase(iterator)` - **Description**: Removes the element pointed to by the given iterator. Returns an iterator to the element following the removed element. - **Parameters**: - `iterator` - An iterator pointing to the element to remove. - **Returns**: An iterator to the element following the removed element. ``` -------------------------------- ### z_tree::map::lower_bound - C++ Range Queries Source: https://context7.com/z-libs/ztree.h/llms.txt Returns an iterator to the first element not less than the given key. This is useful for performing range queries and ordered searches within the map. It requires the ztree header and a comparison function for custom types. ```cpp #include #include static int score_cmp(const int* a, const int* b) { return (*b - *a); // Descending order } #define REGISTER_ZTREE_TYPES(X) \ X(int, std::string, Leaderboard, score_cmp) #include "ztree.h" int main() { z_tree::map board; board[3000] = "Dave"; board[2000] = "Bob"; board[1500] = "Alice"; board[1200] = "Charlie"; std::cout << "Full leaderboard (descending by score):" << std::endl; for (auto entry : board) { std::cout << " " << entry.value() << ": " << entry.key() << " pts" << std::endl; } // Find players with score <= 1800 int cutoff = 1800; auto it = board.lower_bound(cutoff); std::cout << "Players with score <= " << cutoff << ":" << std::endl; for (; it != board.end(); ++it) { std::cout << " " << it.value() << ": " << it.key() << " pts" << std::endl; } return 0; } ``` -------------------------------- ### ztree.h Custom Memory Allocation Override Source: https://github.com/z-libs/ztree.h/blob/main/README.md Allows overriding the default memory allocation functions (`malloc`, `free`) used by ztree.h in C mode. This is achieved by defining `Z_MALLOC` and `Z_FREE` macros before including `ztree.h`, enabling integration with custom allocators like C arenas. ```c #ifndef MY_TREES_H #define MY_TREES_H #include "my_memory.h" // Override global allocators #define Z_MALLOC(sz) my_alloc(sz) #define Z_FREE(p) my_free(p) #include "ztree.h" #endif ``` -------------------------------- ### z_tree::map::erase - Remove Elements Source: https://context7.com/z-libs/ztree.h/llms.txt Removes elements from the map either by their key or by an iterator. Iterator-based erase returns the next valid iterator, which is crucial for safely removing elements during iteration. Requires the ztree header and a comparison function. ```cpp #include static int int_cmp(const int* a, const int* b) { return (*a > *b) - (*a < *b); } #define REGISTER_ZTREE_TYPES(X) \ X(int, int, IntInt, int_cmp) #include "ztree.h" int main() { z_tree::map m; m[10] = 100; m[20] = 200; m[30] = 300; m[40] = 400; std::cout << "Before erase: size=" << m.size() << std::endl; // Erase by key m.erase(20); std::cout << "After erasing key 20: size=" << m.size() << std::endl; std::cout << "Key 20 exists: " << (m.find(20) ? "yes" : "no") << std::endl; // Erase by iterator (returns next valid iterator) auto it = m.begin(); // Points to key 10 it = m.erase(it); // Erases 10, returns iterator to 30 std::cout << "After iterator erase, next key: " << it.key() << std::endl; std::cout << "Remaining entries:" << std::endl; for (auto entry : m) { std::cout << " " << entry.key() << std::endl; } return 0; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.