Sto*_*row 0 c++ arrays stl stdmap allocator
我试图使用固定长度的数组作为a的键std::map,如下面的非编译代码所示:
#include <cstdlib>
#include <iostream>
#include <map>
typedef char myuuid[ 16 ];
template <class T>
class MyAlloc
{
public:
typedef T value_type;
typedef T* pointer;
typedef T& reference;
typedef const T* const_pointer;
typedef const T& const_reference;
template <class U> struct rebind { typedef MyAlloc<U> other; };
MyAlloc() {}
MyAlloc( const MyAlloc& other ) {}
T* allocate( std::size_t n ) { return static_cast<T*>( std::malloc( n * sizeof( value_type ) ) ); }
void deallocate( T* p, std::size_t n ) { std::free( p ); }
};
int main( int argc, char* argv[] )
{
std::map<myuuid, int, std::less<myuuid>, MyAlloc<myuuid> > map;
myuuid myu;
map[ myu ] = 5;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
暂时忽略自定义分配器,如果我正确理解链接的答案,std::map<myuuid, int> map; myuuid myu; map[myu] = 5;失败的原因归结为以下是不可能的:
int main( int argc, char* argv[] )
{
char a[3];
char b[3];
b = a; // Illegal - won't compile
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题:
我理解为什么上述内容是非法的 - 但我是否正确,这证明了为什么std::map<myuuid, int> map; myuuid myu; map[myu] = 5;是非法的?
问题:
std::map<myuuid, int> map; myuuid myu; map[myu] = 5;如果我实现了自定义分配器,我想我可能能够完成编译.我猜想也许a的=(赋值)myuuid会被"重新路由" MyAlloc::allocate(),但这是一个疯狂的,无理的猜测,这似乎是错误的.有没有办法可以修改自定义分配器来解决第一个代码块的编译错误?
我有一个半生不熟的概念,即operator=在myuuid操作数可能被"改道",以自定义的分配器,但我不知道这是否是真正的POD(myuuid只是Typedef的一个POD`).
编译错误太大而无法在此处发布,但有意思的是,第一个错误是:
/usr/include/c++/4.8.3/bits/stl_pair.h: In instantiation of \u2018std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = const char [16]; _T2 = int]\u2019:
/usr/include/c++/4.8.3/bits/stl_map.h:469:59: required from \u2018std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = char [16]; _Tp = int; _Compare = std::less<char [16]>; _Alloc = MyAlloc<char
[16]>; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = int; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = char [16]]\u2019
main.cpp:27:12: required from here
/usr/include/c++/4.8.3/bits/stl_pair.h:113:31: error: array used as initializer
: first(__a), second(__b) { }
Run Code Online (Sandbox Code Playgroud)
有趣的error: array used as initializer是,在引入自定义分配器之前,我试图解决的原始编译错误.所以这似乎是一个递归问题.
问题:
std::map通过使用自定义分配器可以以某种方式使用数组作为键吗?(也许我应该实现一个可选的功能?)或者在所提到的链接上的替代方案是唯一的解决方案吗?(在这些问题的答案中没有提出,但由于自定义分配器有点深奥,我认为值得一个单独的问题)
原始C数组不是表现良好的类型.你不能指定它们或用你想做的无数其他事情.
第二,std::less<char[16]>不起作用.
C++提供std::array,它是一个围绕原始C数组的薄包装器struct.
typedef std::array<char, 16> myuuid;
Run Code Online (Sandbox Code Playgroud)
它甚至还带有内置功能,<通常可以做正确的事情.
所以我们得到:
std::map<myuuid, int> map;
Run Code Online (Sandbox Code Playgroud)
事情有效.
std::array有[]和.data()和.size()和.begin()和.end()和总体表现良好.
如果需要将其转换为指针,只需调用即可.data().