Use a global vector in C ++

advertisements

I have implemented a fast comparison function which uses a look-up table. Since this function is used in multiple classes in the project, I need to make sure that there is only one copy of the look-up table during the whole execution of the program.

The look-up table is a simple vector<int> of size 65536. I wish that this table is initialized at the beginning of the program, not at the time of its first use. How to deal with this problem?

The following code snippet is the current version of my comparison function. I believe that by making lookup_table a static variable, the problem will be resolved only partially, because the lifetime of static variables begins the first time the program flow encounters the declaration.

int fast_compare(const char* array1, const char* array2, int length)
{
    static const vector<int> lookup_table = init_lookup_table();

    // process the input arrays...
    // ...
    return lookup_table[...];
}

vector<int> init_lookup_table()
{
    vector<int> lut(65536);

    // ----------------------------
    // initialize the look-up table
    // ...
    // ...
    // end of initialization
    // ----------------------------

    return lut;
}


I wish that this table is initialized at the beginning of the program, not at the time of its first use.

Why not use a un-named namespace in the cpp file?

#include <numeric>
#include <iterator>
#include <iostream>
#include <vector>

namespace {
    //c++11 version
    static auto const lookup_table = []() -> std::vector<int> {
        std::vector<int> lut(65536);
        iota(begin(lut), end(lut), 0);// init lut here
        return lut;
    }();// invoke the lambda

    //c++ 98 version
    //static const std::vector<int> lookup_table = init_lookup_table();
}

int main()
{
    std::cout<<"lut[32768] = " << lookup_table[32768]<<std::endl;
}

The lambda initialization is explained by Herb Sutter here