Array of characters as a value on a C ++ map

I want to define something like

Map<int, char[5] > myMap;

The above declaration is accepted by the C ++ compiler and no error occurs, but when I do something like this

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

I get an error like:

In file included from /usr/include/c++/4.6/bits/stl_algobase.h:65:0,
                 from /usr/include/c++/4.6/bits/char_traits.h:41,
                 from /usr/include/c++/4.6/ios:41,
                 from /usr/include/c++/4.6/ostream:40,
                 from /usr/include/c++/4.6/iostream:40,
                 from charMap.cpp:1:
/usr/include/c++/4.6/bits/stl_pair.h: In constructor ‘std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = int, _T2 = char [5]]’:
charMap.cpp:9:42:   instantiated from here
/usr/include/c++/4.6/bits/stl_pair.h:104:31: error: array used as initializer
/usr/include/c++/4.6/bits/stl_pair.h: In constructor ‘std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = int, _U2 = char [5], _T1 = const int, _T2 = char [5]]’:
charMap.cpp:9:43:   instantiated from here
/usr/include/c++/4.6/bits/stl_pair.h:109:39: error: array used as initializer

It is important for me to define an array of characters of a fixed size, since it optimizes the operation of my network stream. Is there any way to achieve this? I do not want to use char *or std::string.

+5
source share
4 answers

One way is to wrap an array of fixed-size characters as a structure.

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;
}
+2
source

I understand your performance requirements (since I do similar things too), but using character arrays this way is pretty dangerous.

++ 11, std::array. :

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

++ 11, boost::array.

+7

.

  • std::vector

  • 5 .

  • 5 .

  • Instead of using an array, create a new structone that accepts 3 elements. Do it map<int, newstructtype>. Or wrap your array in structand it will work too.

\

struct ArrayMap
{
    int color[5];
};

/

+1
source

According to the documentation, a pair may contain (and be defined for) different classes. The C array is not a class, but a construct. You must define your own class with overloaded operator[](). Comparison operators are also needed.

-2
source

All Articles