将大量数据初始化为C++容器的最佳方法是什么?

Nah*_*Nah 4 c++ containers constants hardcode large-data

例如:

InitEmployee()
{
    vector<Employee> employeeList = {
        Employee("Clark Kent",0),
        Employee("Bruce Wayne",1),
        ...
        Employee("Hal Jordan",65535)
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法从文件或数据库查询,因为此程序需要在单个可执行文件中,因此所有常量数据必须是硬编码的.我实际上使用boost的multi_index_container按名称和id进行快速查找但是为了简单起见,我在这里使用了vector作为示例.问题是我在单个函数中没有那么多(2 ^ 16)个常量数据而没有堆栈溢出.有没有更好的方法来初始化这个列表而不拆分功能?

我正在使用VC12.谢谢!

更新

见选择的答案.正如其他人所提到的,使用static会强制它继续数据而不是堆栈.这就是我最终得到的结果:

InitEmployee()
{
    static Employee employeeList[] = {
        {"Clark Kent",0},
        {"Bruce Wayne",1},
        ...
        {"Hal Jordan",65535}
    }

    vector<Employee*> employeeVec;
    int count = sizeof(employeeList) / sizeof(Employee);
    for (int i = 0; i < count; i++)
    {
        employeeVec.emplace(&employeeList[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是Employee类使用的是字符串类而不是c-string,所以我不想在内存中使用它的两个副本.这样我最终只得到指针的额外内存,这仍然是很多,但我相信这是最好的选择!也适用于multi_index_container!谢谢

Ben*_*ley 5

使用静态数组存储初始化数据.

InitEmployee()
{
    static char const* const names[] = {
        "Clark Kent",
        "Bruce Wayne",
        ...
        "Hal Jordan"
    };

    size_t const n = sizeof(names) / sizeof(*names);

    vector<Employee> employeeList;
    employeeList.reserve(n);
    for (size_t i=0; i<n; ++i)
        employeeList.emplace_back(names[i],i);
    ...
}
Run Code Online (Sandbox Code Playgroud)