Question

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)

    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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top