如何为将指针存储在std :: map中的模板类编写副本构造函数?
|
我刚开始使用c ++,但在制作名为auto_map的模板类时遇到了一些问题,该模板类使用std :: map来存储对象而不是对象的指针。
就像是:
std::map<K*, V*, cmp> m;
我这样使用:
auto_map<std::string, std::string> t;
t.insert( new std::string( \"A\" ), new std::string( \"B\" ) );
千次曝光出价是:
struct cmp
{
bool operator()(K *a, K *b) { return *a < *b; }
bool operator== (K *a) { return (*a); }
};
插入功能会在插入之前搜索所有重复项:
void insert(K* k, V* v)
{
for (typename std::map<K*, V*, cmp>::iterator i=m.begin(); i!=m.end(); ++i)
{
if ( (*k) == (*(*i).first) )
{
delete (*i).first;
delete (*i).second;
m.erase(i);
}
}
m.insert(std::make_pair(k,v));
}
和构造函数:
auto_map(){}
~auto_map()
{
for (typename std::map<K*, V*, cmp>::iterator i=m.begin(); i!=m.end(); ++i)
{
delete (*i).first;
delete (*i).second;
m.erase(i);
}
}
这些工作正常,但现在您可能已经明白了。
因此,问题来了,我不太确定:
如何为它编写复制构造函数?
auto_map (auto_map& original)
{
for (typename std::map<K*, V*, cmp>::iterator i=original.m.begin(); i!=original.m.end(); ++i)
{
// what goes in here that will call each objects copy-constructor?
// how not to get complained about invalid conversions?...
// K newk = (*(*i).first);
// V newv = (*(*i).second);
// m.insert(std::make_pair(newk, newv));
// gives compiler error: cannot convert ‘const CntInteger’ to ‘CntInteger* const’ in initialization
// cannot convert ‘const CntInteger’ to ‘CntInteger*’ in initialization
}
};
非常感谢您的回答和更正!
没有找到相关结果
已邀请:
2 个回复
呸溉
编写新的副本构造函数。 接下来,您确定您真的要针对容器再次使用O(log n)查找来实现映射的整个(二叉树)结构,并增加memory7ѭ的内存管理注意事项(考虑使用自定义删除器的对象)吗?为什么不简单地在地图上放入8英镑呢?
更新:您可以使用Boost \的指针容器吗?还是您还需要将值用作指针?值
的
呢?
碉罕城爸