Character Array as a value in C++ map

大憨熊 提交于 2019-11-30 20:27:37

One way is to wrap the fixed size character array as a struct.

struct FiveChar
{
   FiveChar(char in[5]) { memcpy(data, in, 5); }
   char& operator[](unsigned int idx) { return data[idx]; }
   char data[5];
};

int main(void)
{
   char arr[5] = "sdf";
   map<int, FiveChar> myMap;
   myMap.insert(pair<int, FiveChar>(0, arr));
   return 0;
}

I understand your performance requirements (since I do similar things too), but using character arrays in that way is rather unsafe.

If you have access to C++11 you could use std::array. Then you could define your map like:

map <int, array<char, 5>> myMap;

If you cannot use C++11, then you could use boost::array.

You cannot use an array in a standard container.

  1. Use an std::vector instead of an array

  2. Use a map of pointers to arrays of 5 elements.

  3. Use boost tuples instead of arrays of 5 elements.

  4. Instead of using an array make a new struct that takes 3 elements. Make the map<int, newstructtype>. Or wrap your array in a struct and that will work too.

\

struct ArrayMap
{
    int color[5];
};

/

According to documentation pair can hold (and be defined for) distinct classes. C array is not a class, but a construct. You must define your own class with overloaded operator[](). Might need comparison operators as well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!