在编译时(C ++)创建大型hashmap的最佳方法?
-
05-07-2019 - |
题
在我的应用程序中,我需要一个哈希映射,将字符串映射到大量静态对象。映射在应用期间保持固定。是否有一种简单的方法可以在编译时预先生成映射,而不是在应用程序启动时逐个元素地构建映射?
解决方案
查找 gperf ,它会为您生成完美哈希的代码。
其他提示
查看Burtlebob完美的散列函数。根据我的经验,它比gperf更灵活。 http://burtleburtle.net/bob/hash/perfect.html
您可以编写一个简单的代码生成器,使用映射发出头文件,然后在构建过程中将其作为预构建步骤运行。
您正在寻找 Boost。分配的 map_list_of
。它也适用于哈希映射。
#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 );
}
不隶属于 StackOverflow