![](/img/trans.png)
[英]How to update the vectors in a std::unordered_map<std::string, std::vector<int>> without copying?
[英]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-dynamic-allocated-objects-cause-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],因此它在實際匯編代碼中可能沒有區別。
按鍵無序地圖訪問非常快。 您可以參考該元素並對其進行處理,但否則這很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.