Does std::stack expose iterators?

后端 未结 5 1237
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 08:57

Does the std::stack in the C++ STL expose any iterators of the underlying container or should I use that container directly?

5条回答
  •  既然无缘
    2020-11-29 09:32

    Yor are asking

    Does std::stack expose iterators?

    Many people gave answers. If my English would be better, I would maybe also understand the exact meaning of 'expose'.

    If we are referring to the STL and the class std::stack and the pre defined functions defined herein, the answer is NO.

    My guess would be that you are asking, because you want to have iterators.

    So, if we go one step further, we have the function top(). And top() can be interpreted as a dereferenced iterator. With that, we can easily define Iterators to stack elements. The memory of the stack is guaranteed to be contiguous.

    See below. We are defining and using iterators for std::copy:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    using Number = int;
    using UnderlyingContainer = std::vector;
    using Stack = std::stack< Number, UnderlyingContainer>;
    
    using StackIterator = const Number *;
    
    std::istringstream testData("5 8 1 4 9 3");
    
    int main()
    {
        // Put the test data onto the stack
        Stack stack{ UnderlyingContainer {std::istream_iterator(testData),std::istream_iterator()} };
    
        // Print the test data
        // Get iterators
        StackIterator end = &stack.top() + 1;
        StackIterator begin = end - stack.size();
    
        if (not stack.empty())
            std::copy(begin, end, std::ostream_iterator(std::cout, "\n"));
        return 0;
    }
    
    

    So you can create iterators for a stack. But, caveat:

    The std::stack intentionally hides its elements under the hood. So, if you write-access the data, I would see it as a design fault. Read-access through const pointers/iterators is for me OK. But maybe you should better use a std::vector . . .

提交回复
热议问题