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
我有一个全局变量:
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],因此在实际汇编代码中可能没有区别。
按键访问无序地图非常快。您可以引用该元素并对其进行处理,但除此之外,这很好。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- EASTL矢量<向量<int>>连续的
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 'structstd::对<int,int>'没有名为'push_back'