无序映射中运算符[]的C++专门化

C++ specialization of operator[] in unordered_map

本文关键字:C++ 专门化 映射 运算符 无序      更新时间:2023-10-16

我一直在使用unordered_map<int, myObject>和指向无序映射中对象的myObject*指针。这种方法已经运行了一段时间,但我最近发现,我错误地认为添加到无序映射中的myObject的内存位置将始终保持不变。

在无序映射中添加和删除元素时,我可以使用unordered_map<int, myObject*>newdelete来解决这个问题。

由于我有相当多的代码,我不想在代码中修改无序映射的每个地方都添加newdelete,我宁愿尝试重载unordered_map::operator[]unordered_map::erase(),这样newdelete的使用就可以透明地进行,而且我不必更改现有的代码。unordered_map::operator[]然后可以返回对myObject本身的引用,而不是指针。

我试图继承unordered_map,但我不确定应该如何添加模板参数列表:

using namespace std;
template<class _Kty,
class _Ty,
class _Hasher = hash<_Kty>,
class _Keyeq = equal_to<_Kty>,
class _Alloc = allocator<pair<const _Kty, _Ty> > >
class  my_unordered_map : public unordered_map<_Umap_traits<_Kty, _Ty,
_Uhash_compare<_Kty, _Hasher, _Keyeq>, _Alloc, false> >
{
};

但我收到的错误如下:

error C2976: 'std::unordered_map' : too few template arguments
error C2955: 'std::unordered_map' : use of class template requires template argument list

然后我意识到,当将myObject*类型与unordered_map一起使用时,可能会向std添加专门化,但我不确定是否有可能用专门化重载operator[]

我很感激我能得到的任何帮助,谢谢!

编辑:

我现在已经创建了一个template <class mapped_type>类,其中unordered_map<int, mapped_type*>作为内部结构。operator[]相当简单地包括:

template <class mapped_type> class MyMap {
public:
std::unordered_map<int, mapped_type*> internal_map;
mapped_type& operator[](int&& _Keyval)
{   // find element matching _Keyval or insert with default mapped
mapped_type*& ptr = internal_map[_Keyval];
if (ptr == nullptr) ptr = new mapped_type();
return *ptr;
}
}
void erase(const int& _Keyval)
{   // erase and count all that match _Keyval
mapped_type* ptr = internal_map[_Keyval];
if (ptr) delete ptr;
internal_map.erase(_Keyval);
}
void clear()
{   // erase all
internal_map.clear();
}

现在的问题是擦除方法(默认方法包含在std::_Hash中)。我真的不需要迭代器,所以我想最好的方法可能是先使用operator[]方法来找到条目,然后在从internal_map中删除它之前使用delete,或者你有其他更合适的想法吗?

编辑:添加了擦除建议。这很有道理,对吧?

要从std::unordered_map继承,使用就足够了

template <class T,class V> 
class MyMap : public unordered_map<T, V>

如果可以使用std分配器和hash函数。但是要注意,在标准容器中没有虚拟析构函数。

不管怎样,在我看来,你最终想要做的事情就像你想要一个侵入性容器。如果是的话,那么就存在这个相关的so问题。