Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize large amount of data into a C++ container?

For example:

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

I cannot query from file or DB as this program needs to be in a single executable so all the constant data must be hard coded. I'm actually using boost's multi_index_container for fast lookup by name and id but for simplicity sake I used vector here as example. The problem is that I cannot have that many (2^16) constant data in a single function without stack overflow. Are there any better ways initialize this list without splitting up the function?

I'm using VC12. Thanks!

Update

See chosen answer. As others have mentioned using static will force it to go on data rather than stack. This is what I ended up with:

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

The thing was Employee class used a string class rather than c-string, so I didn't want two copies of it in memory. This way I end up with just the extra memory for pointers, which is still a lot but I believe this is the best option! Also works with multi_index_container! Thanks

like image 631
Nah Avatar asked Apr 01 '14 20:04

Nah


1 Answers

Use a static array to store the initialization data.

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);
    ...
}
like image 126
Benjamin Lindley Avatar answered Sep 28 '22 23:09

Benjamin Lindley