unordered_map (A)constructor, (B) delete allocate in, (C)inh

unordered_map (A)constructor, (B) delete allocate in, (C)inherit from

本文关键字:allocate inh in delete constructor map unordered      更新时间:2023-10-16

Comparison是类名时,我的声明是unordered_map<Comparison,int> Chs。现在我有几个问题;

。当构造函数调用时,我如何插入一些元素(如vector) ?

。:

unordered_map<Comparison,int> Chs =
{
    (new Equal_to<int>,10),
    (new Not_equal_to<int>,30),        
    (new Greater<int>,20)
};

这段代码现在得到编译错误。

B。如何释放分配的内存(与new)在这个声明?

C。在继承类:

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

我应该如何编写RC构造函数,使其可以初始化的元素,如一个问题?

谢谢你,很抱歉我的英语很差。

你最好不要继承标准容器,它们不是为它设计的。

此外,如前所述,要使包含的比较具有多态行为,您需要存储引用或指针。指针的使用要简单得多。

为了避免担心释放内存,使用智能指针(std::unique_ptr或std::shared_ptr)。

下面的代码片段显示了上述大部分代码的工作原理,包括如何在自己的容器类(RC<>)上进行统一初始化:
#include <unordered_map>
#include <memory>
struct Comparison {};
template <class T> struct Equal_to     : Comparison { };
template <class T> struct Not_equal_to : Comparison { };
template <class T> struct Greater      : Comparison { };
template <class T,class V>
class RC
{
    typedef std::unordered_map<T,V> comps_t;
    typedef typename comps_t::value_type value_type;
    comps_t comps;
  public:
    RC(std::initializer_list<value_type> init) : comps(init) { }
};
int main(int argc, const char *argv[])
{
    RC<std::shared_ptr<Comparison>, int> demo = { 
        { std::make_shared<Equal_to<int>>(),10 },
        { std::make_shared<Not_equal_to<int>>(),30 },        
        { std::make_shared<Greater<int>>(),20 } };
    return 0;
}

在(可能无用的优化)部门,如果它不与其他构造函数需求冲突,您可以拥有完美的转发构造函数。这将有利于正确地支持move语义:

template <typename... A>
    RC(A&&... a) : comps(std::forward<A...>(a...)) { }