【问题标题】:allocate an std map with list pointer value in c++在 C++ 中分配具有列表指针值的 std 映射
【发布时间】:2015-08-12 07:49:13
【问题描述】:

我正在尝试为我的 std 映射的每个键分配一个列表,但是使用 new 运算符我得到一些错误(没有预定义的构造函数是 find 和其他),为什么?

我的代码是这样的:

std::map<QString, *std::list<ExecutionGUIObject*>> execEvtMap;

execEvtMap["t1"] = new std::list<ExecutionGUIObject*>;

【问题讨论】:

  • 请包括错误的确切文本。

标签: c++ list pointers dictionary std


【解决方案1】:
*std::list<ExecutionGUIObject*>

不是有效类型,因此不是std::map 模板的有效参数。你可能是说

std::list<ExecutionGUIObject*>*

表示“指向 ExecutionGUIObject 对象的指针列表的指针”。

【讨论】:

    【解决方案2】:

    正如Frerich Raabe 所述,这是您的地图声明中的一个小语法错误。但是通过动态分配std::list,你什么也得不到,那么为什么还要找麻烦呢?只需使用列表映射即可。

    std::map<QString, std::list<ExecutionGUIObject*>> execEvtMap;
    
    // Creates a new (empty) list for key "t1" if one does not already exist.
    void(execEvtMap["t1"]);
    
    // Creates a new list for key "t1", or clears the existing one.
    execEvtMap["t1"].clear();
    
    // Erases a key and its list
    execEvtMap.erase("t1");
    

    如果这张地图拥有 ExecutionGUIObject 的,你也需要调整它:

    std::map<QString, std::list<std::unique_ptr<ExecutionGUIObject>>> execEvtMap;
    

    【讨论】:

    • 如果我必须从类中公开列表(如 get 方法),这两种方法的效率是否相同? @昆汀
    • @Daniel 比如std::list&lt;...&gt; &amp;getList(QString key); ?是的,同样的费用。事实上,您只能通过减少动态分配来加快速度。另外,没有疯狂的拥有原始指针来管理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    相关资源
    最近更新 更多