0

I'm implementing a data structure, the X-fast trie, in which several hash maps are needed. To store the maps, which make up the level-search structure of the trie, I use a number of std::vectors and a certain perfect hash algorithm much like this:

struct node_value
{
    // One out-edge.
    ...
};

typedef std::array<node_value, 2> node;                             // Two out-edges for each node.
typedef std::array<std::vector<node>, 32> level_search_structure;   // One vector for each level.

The keys are uint32_t in this case. The vector indices to be used are determined by the hash algorithm.

I'm somewhat concerned with memory locality. If the contents of the vectors were allocated consecutively, spatial locality would be improved, or so I believe. My question is, what would be a good way to accomplish this? I'm thinking of replacing the vectors with C-style array wrappers, the memory for which would be managed by a separate object. Each of the wrappers would take a starting index and a length to be used from the allocated buffer, something like this:

std::unique_ptr<node[]> array_ptr(new node[...]);

// In case the first three levels required space for 1, 2, and 4 nodes respectively:
array_wrapper lss_1(array_ptr.get(), 0, 1); // Starts from array_ptr's index 0, capacity of 1 
array_wrapper lss_2(array_ptr.get(), 1, 2); // Starts from index 1, capacity of 2
array_wrapper lss_3(array_ptr.get(), 3, 4); // Starts from index 3, capacity of 4
...

Are there better alternatives?

tsnorri
  • 1,966
  • 5
  • 21
  • 29
  • Have a look at [allocators](http://stackoverflow.com/questions/31358804/whats-the-advantage-of-using-stdallocator-instead-of-new-in-c). – user657267 Feb 11 '16 at 09:17
  • Using a custom allocator for the vectors? – tsnorri Feb 11 '16 at 09:24
  • 1
    indeed, if you abstract the memory allocation into its own allocator you can reuse it with any compatible container or class. There's some non-default [allocators](http://en.cppreference.com/w/cpp/experimental/lib_extensions#Type-erased_and_polymorphic_allocators) in the library extensions TS although I don't know if any lib has implemented them yet (well boost at least has). [This](http://en.cppreference.com/w/cpp/experimental/monotonic_buffer_resource) sounds like it might be at least close to what you're looking for. – user657267 Feb 11 '16 at 11:50

0 Answers0