Does std::stack expose iterators?

后端 未结 5 1238
爱一瞬间的悲伤
爱一瞬间的悲伤 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:44

    The std::stack does expose its underlying container (and therefore iterators) to subclasses through its protected interface. The std::stack's underlying container object corresponds to the (protected) data member c. So if you want to access them, you could extend std::stack a little.

    template>
    class iterable_stack
    : public std::stack
    {
        using std::stack::c;
    
    public:
    
        // expose just the iterators of the underlying container
        auto begin() { return std::begin(c); }
        auto end() { return std::end(c); }
    
        auto begin() const { return std::begin(c); }
        auto end() const { return std::end(c); }
    };
    
    int main()
    {
        iterable_stack st;
    
        st.push(2);
        st.push(5);
        st.push(3);
        st.push(7);
        st.push(9);
    
        for(auto i: st)
            std::cout << i << ' ';
        std::cout << '\n';
    }
    

    Output:

    2 5 3 7 9 
    

提交回复
热议问题