【问题标题】:C++11: std::unordered_map<int, std::stack<int>> getting values from map without copying multiple timesC++11:std::unordered_map<int, std::stack<int>> 从映射中获取值而不复制多次
【发布时间】:2014-01-21 11:39:48
【问题描述】:

我有一个全局变量:

std::unordered_map<int, std::stack<int>> intTable;

为了补充这一点,我目前这样做:(我已经看到 C++11 初始化列表,但我不确定我是否会遇到这个 Visual C++ 11 2013 错误 --> http://connect.microsoft.com/VisualStudio/feedback/details/807966/initializer-lists-with-nested-dynamically-allocated-objects-causes-memory-leak

    std::stack<int> s;
    s.push(10);

那我做

    intTable[integerKey] = s;

然后我有时需要添加到堆栈中,并检查它的顶部值,如果它大于一个值,我需要弹出它并从映射中删除键:

    intTable[integerKey].push(20);

    if (intTable[integerKey].top() >= someIntegerValue)
    {
       intTable[integerKey].pop();

       if (intTable[integerKey]->size() == 0)
       {
          intTable.erase(integerKey);
       }
    }

我的问题是有更好的方法吗?例如,我看到的一个低效率是我多次索引到地图中。有可能避免这种情况吗?如何在不复制的情况下存储对 intTable[integerKey] 的引用?

【问题讨论】:

    标签: c++ c++11 vector stack unordered-map


    【解决方案1】:

    你可以的

    std::stack<int> &localReference = intTable[integerKey];
    

    在您的函数开始时并随后访问本地引用,尽管编译器很可能会在本地函数范围内优化掉 intTable[integerKey],因此它可能与实际的汇编代码没有区别。

    【讨论】:

    • 另外,如果你想在不搜索的情况下擦除,使用find获取映射到地图的迭代器。
    • 我不知道我可以通过迭代器来删除密钥!
    • 如果我有迭代器,我是否也可以使用它以某种方式从地图中检索值?我目前总是做 .find() .. 然后如果它存在,我通过做 mymap[key] ...
    【解决方案2】:

    Map 成员在访问时使用默认构造函数进行初始化。

    std::stack<int> &localReference = intTable[integerKey];
    

    将分配堆栈(如果它不存在),并返回对堆栈的引用。

    【讨论】:

      【解决方案3】:

      按键访问无序地图非常快。您可以引用该元素并对其进行处理,否则这很好。

      【讨论】:

        猜你喜欢
        • 2013-07-11
        • 1970-01-01
        • 2015-10-22
        • 1970-01-01
        • 1970-01-01
        • 2012-05-07
        • 1970-01-01
        • 2022-09-28
        • 1970-01-01
        相关资源
        最近更新 更多