Search code examples
c++initializationlookup-tablesarrays

create and initialize a static const char array as Ascii Look up Table in c++


Hey I tried to make a look up table to switch chars to upper case:

struct X {
    static const char lut[256];
};

int main(int argc, char** argv) {
    for(int i = 0; i < 256; i++) {
        char c = (char)i;
        if (c <= 'z' && c > 'Z') {
            X::lut[i]= (c-32);  
        }
        X::lut[i]=c;
    }
    return 0;
}

I know that this is the wrong way:( Can someone show me to do this correct?


Solution

  • You may use the following (in C++11):

    #include <array>
    #include <cctype>
    
    std::array<char, 256> to_upper_array()
    {
        std::array<char, 256> res;
    
        for (int i = 0; i != 256; ++i) {
            res[i] = char(std::toupper(i));
        }
        return res;
    }
    
    struct X {
        static const std::array<char, 256> lut;
    };
    
    const std::array<char, 256> X::lut = to_upper_array();