c++gccvectorinitializationgcc4.4

How to implement large vector initialization that compiles with gcc-4.4?


I have a list of 20k known strings that I know at compile time and will never change. A sort of non-configurable dictionary. I do not want to load it in run time from a file, because this would imply a lot of unnecessary architecture: finding the file in a certain path, a configuration file to indicate the path, etc.

I came up with a solution like this in C++:

In a.cpp:

std::vector<std::string> dic;
dic.reserve(20000);
#define VECTOR_DIC_ dic;
#include values.inl
#undef VECTOR_DIC_

then in the values.inl, a lis of 20k push_back calls, like this:

VECTOR_DIC_.push_back("string1");
VECTOR_DIC_.push_back("string2");
...
VECTOR_DIC_.push_back("string20000");

This code compiles and works properly with gcc-4.8 on Debian but fails to compile with gcc-4.4, gcc-4.4 never finishes to compile the a.cpp file.

Why does gcc-4.4 not support this type of large initialization? Also, is there a design pattern for such large initialization for known values at compile time?


Solution

  • Use an array of const char * and then initialize your vector from it:

    #include <string>
    #include <vector>
    
    char const * const S[] = {
        "string1",
        "string2"
    };
    
    const std::size_t N_STRINGS = sizeof(S) / sizeof(*S);
    
    const std::vector<std::string> dic(S, S + N_STRINGS);
    

    This compiles fine (did not test with 20k strings though) with g++ 4.4.7.