Tony the Pony
Tony the Pony

Reputation: 41367

Best way to create large hashmap at compile time (C++)?

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?

Upvotes: 1

Views: 3733

Answers (5)

Yuki
Yuki

Reputation: 4173

You can try to use Compile-time Hash Map for C++. This solution requires a compiler supporting C++-14 standard.

Upvotes: 0

StilesCrisis
StilesCrisis

Reputation: 16290

Check out Burtlebob's perfect hashing function. In my experience it is more flexible than gperf. http://burtleburtle.net/bob/hash/perfect.html

Upvotes: 2

GManNickG
GManNickG

Reputation: 503913

Look up gperf, it generates code for you that will perfectly hash.

Upvotes: 3

rlbond
rlbond

Reputation: 67779

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 );  
}

Upvotes: 1

Eric J.
Eric J.

Reputation: 150108

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.

Upvotes: 1

Related Questions