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

For instance:

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

I cannot request a file or database, since this program must be in one executable file, so all persistent data must be hard-coded. I actually use boost multi_index_container to quickly search by name and id, but for simplicity I used the vector here as an example. The problem is that I cannot have as many (2 ^ 16) constant data in one function without. Is there a better way to initialize this list without splitting a function?

I am using VC12. Thank!

Update

See the selected answer. As mentioned, using static will force it to use data, not the stack. This is what I came across:

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

, Employee , c-, . , , - , , ! multi_index_container!

+4
4

.

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);
    ...
}
+5

, ? , :

const char *data = R"(
Clark Kent,0
Bruce Wayne,1
...
Hal Jordan,65535)"

/* ... */

int main()
{
    /* ... */
}

, DB .

0

, spring . Visual Studio. Visual Studio 2012 12.0 (, VS2012 11.0). 2013 ( 12.0), , ++ 11 (, . FAQ)

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

Initializer lists rely on the semantics of moving the C ++ 11 rvalue language to make sure that you are only done with one copy of the data in the application.

Another option might be to use boost::assign(see docs ), which means that you can use the same kind of syntax, but dynamic allocation:

#include <boost/assign/std/vector.hpp> // for 'operator+=()'
using namespace boost::assign; // bring operator+= into scope
vector<Employee> employeeList;
employeeList += Employee("Clark Kent", 0),
                Employee("Bruce Wayne", 1), ...
0
source

Source: https://habr.com/ru/post/1534532/


All Articles