Initialize sparse static array

后端 未结 2 929
猫巷女王i
猫巷女王i 2020-12-22 03:05

I need to initialize a static array. Not all of the values are sequential.

Something like this works fine for a sequential array:

class Foo {

  publ         


        
相关标签:
2条回答
  • 2020-12-22 03:52

    I would suggest you to use std::map<int, std::string> (or unordered_map if you have C++11 support) instead of the array. You can then insert into this map with the code : m[67] = "Sun" and retrieve items using std::string s = m[67];.

    0 讨论(0)
  • 2020-12-22 03:57

    Here's one old-school approach:

    class NameArray {
      public:
        NameArray()
        {
          array[67] = "Sun";
          array[68] = "Moon";
        }
    
        const char *operator[](size_t index) const
        {
          assert(index<256);
          return array[index];
        }
    
    
      private:
        const char * array[256];
    };
    
    class Foo {
      public:
        static NameArray name;
    };
    
    NameArray Foo::name;
    

    By wrapping the array in a class, you can make sure it gets constructed with the values that you want. You can also do bounds checking.

    0 讨论(0)
提交回复
热议问题