[英]C++11: std::unordered_map<int, std::stack<int>> getting values from map without copying multiple times
I have a global variable: 我有一个全局变量:
std::unordered_map<int, std::stack<int>> intTable;
To add to this, I do this currently: (I've seen C++11 initializer lists, but I'm not sure if I'll hit this Visual C++ 11 2013 bug --> http://connect.microsoft.com/VisualStudio/feedback/details/807966/initializer-lists-with-nested-dynamically-allocated-objects-causes-memory-leak ) 为了补充这一点,我现在这样做:(我已经看过C ++ 11初始化列表,但我不确定我是否会遇到这个Visual C ++ 11 2013错误 - > http://connect.microsoft。 com / VisualStudio / feedback / details / 807966 / initializer-lists-with-nested-dynamic-allocated-objects-cause-memory-leak )
std::stack<int> s;
s.push(10);
then I do 那我呢
intTable[integerKey] = s;
I then need to add to the stack sometimes, and check its top value so, and if it is greater than a value, I need to pop it and erase the key from the map: 然后我需要有时添加到堆栈,并检查它的最高值,如果它大于一个值,我需要弹出它并从地图中删除键:
intTable[integerKey].push(20);
if (intTable[integerKey].top() >= someIntegerValue)
{
intTable[integerKey].pop();
if (intTable[integerKey]->size() == 0)
{
intTable.erase(integerKey);
}
}
My question is there a better way of doing this? 我的问题是有更好的方法吗? For example one inefficieny I see is that I'm indexing into the map multiple times.
例如,我看到的一个低效率是我多次索引到地图中。 Is it possible to avoid that?
有可能避免这种情况吗? How can I store a reference to the intTable[integerKey] without copying it?
如何在不复制的情况下存储对intTable [integerKey]的引用?
Map members are initialized with the default constructor when accessed. 访问时,使用默认构造函数初始化映射成员。
std::stack<int> &localReference = intTable[integerKey];
Will allocate the stack (if it does not exist), and return a reference to the stack. 将分配堆栈(如果它不存在),并返回对堆栈的引用。
You can do 你可以做
std::stack<int> &localReference = intTable[integerKey];
In beginning of your function and access local reference afterwards, although compiler will most likely optimize away intTable[integerKey] anyways within the scope of local function so it may be no difference in actual assembly code. 在函数开始之后,访问本地引用,尽管编译器很可能在本地函数的范围内优化远离intTable [integerKey],因此它在实际汇编代码中可能没有区别。
Unordered map access by key is really fast. 按键无序地图访问非常快。 You could take a reference to the element and work on that, but otherwise this is fine.
您可以参考该元素并对其进行处理,但否则这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.