Best way to create large hashmap at compile time (C++)?
-
05-07-2019 - |
Question
In my application, I need a hash map mapping strings to a large number of static objects. The mappings remain fixed for the duration of the application. Is there an easy way to pre-generate the mappings at compile time rather than building it element-by-element when the application starts?
Solution
Look up gperf, it generates code for you that will perfectly hash.
OTHER TIPS
Check out Burtlebob's perfect hashing function. In my experience it is more flexible than gperf. http://burtleburtle.net/bob/hash/perfect.html
You could write a simple code generator that emits a header file with the mappings, and run that as a pre-build step in your build process.
You're looking for Boost.Assign's map_list_of
. It works for hashmaps too.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/assert.hpp>
#include <map>
using namespace std;
using namespace boost::assign; // bring 'map_list_of()' into scope
{
map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
BOOST_ASSERT( next.size() == 5 );
BOOST_ASSERT( next[ 1 ] == 2 );
BOOST_ASSERT( next[ 5 ] == 6 );
// or we can use 'list_of()' by specifying what type
// the list consists of
next = list_of< pair<int,int> >(6,7)(7,8)(8,9);
BOOST_ASSERT( next.size() == 3 );
BOOST_ASSERT( next[ 6 ] == 7 );
BOOST_ASSERT( next[ 8 ] == 9 );
}