我一直在使用 unordered_map<int, myObject>
与 myObject*
指向无序映射中对象的指针。这已经工作了一段时间,但我最近发现我错误地认为添加到无序映射中的 myObject 的内存位置将始终保持不变。
我可以使用 unordered_map<int, myObject*>
解决问题和 new
和 delete
在无序映射中添加和删除元素时。
因为我有很多代码,所以我不想添加 new
和 delete
在我修改无序映射的代码中的每个地方,我宁愿尝试重载 unordered_map::operator[]
和 unordered_map::erase()
这样 new
的用法和 delete
会透明地发生,我不必更改我现有的代码。 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*
时可以为 std 添加一个特化输入 unordered_map
, 但我不确定是否有可能重载 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[]
方法首先找到条目然后使用 delete
在将其从 internal_map
中删除之前,或者您还有其他更合适的想法吗?
编辑:添加了删除建议。这说得通吗?
最佳答案
要从 std::unordered_map
继承,使用它就足够了
template <class T,class V>
class MyMap : public unordered_map<T, V>
如果您可以使用 std 分配器和哈希函数。但请注意,标准容器中没有虚拟析构函数。
关于unordered_map 中 operator[] 的 C++ 特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064979/