Using STL Vector with Stack Storage
Problem:
Finding a C vector-like class that utilizes stack storage instead of the heap.
Solution:
Chromium's stack_container.h provides a StackVector class that perfectly fits the requirement. It behaves almost identically to an ordinary vector but allocates data on the stack.
Usage:
<code class="cpp">char buffer[4096];</code>
<code class="cpp">stack_vector<match_item> matches(buffer, sizeof(buffer));</code>
Alternatively, the buffer can be allocated internally by the class:
<code class="cpp">stack_vector<match_item, 256> matches;</code>
<code class="cpp">typedef std::pair<const char *, const char *> comp_list_item; static const size_t comp_list_alloc_size = 128; typedef StackAllocator<comp_list_item, comp_list_alloc_size> comp_list_alloc_type;</code>
<code class="cpp">comp_list_alloc_type::Source match_list_buffer; comp_list_alloc_type match_list_alloc(&match_list_buffer); comp_list_type match_list(match_list_alloc);</code>
<code class="cpp">match_list.reserve(comp_list_alloc_size);</code>
Benefits:
The above is the detailed content of How to Use a Stack-Based Vector in C ?. For more information, please follow other related articles on the PHP Chinese website!