I want to define something like
Map<int, char[5] > myMap;
The above declaration is accepted by c++ compiler and no error is thrown 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 error as:
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 a fixed size character array because it optimizes my network stream operation. Is there any way to achieve it? I do not want to use char *
or std::string
.
In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings. C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).
char *array = "One good thing about music"; declares a pointer array and make it point to a constant array of 31 characters. char array[] = "One, good, thing, about, music"; declares an array of characters, containing 31 characters.
In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With