C++11:std::unordered_map<int,std::stack<int>> 从映射获取值而无需多次复制

C++11: std::unordered_map<int, std::stack<int>> getting values from map without copying multiple times

本文关键字:gt int lt std 获取 复制 stack unordered map C++11 映射      更新时间:2023-10-16

我有一个全局变量:

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] 的引用?

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

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

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

你可以做

std::stack<int> &localReference = intTable[integerKey];
在函数的

开头和之后访问本地引用,尽管编译器很可能会在本地函数的范围内优化 intTable[integerKey],因此在实际汇编代码中可能没有区别。

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