std :: stack是否公开了迭代器?

时间:2009-02-08 07:53:07

标签: c++ stl stack

C ++ STL中的std::stack是否公开了底层容器的任何迭代器,还是应该直接使用该容器?

5 个答案:

答案 0 :(得分:37)

根据堆栈的定义,堆栈没有迭代器。如果需要使用迭代器进行堆栈,则需要在其他容器(std :: list,std :: vector等)之上自己实现它。 Stack doc is here

P.S。根据我从Iraimbilanja得到的评论,std :: stack默认使用std :: deque来实现。

答案 1 :(得分:12)

如果需要带迭代器的堆栈,则有两种选择。使用push_back(),pop_back()的std :: vector。 std :: deque与push_back()/ pop_back()或push_front()/ pop_front()。

答案 2 :(得分:2)

std::stack确实通过其受保护的接口将其底层容器(以及迭代器)暴露给子类std::stack的基础容器对象对应于(受保护的)数据成员c。 因此,如果您想要访问它们,可以稍微延长std::stack

template<typename T, typename Container = std::deque<T>>
class iterable_stack
: public std::stack<T, Container>
{
    using std::stack<T, Container>::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<int> 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';
}

<强>输出:

2 5 3 7 9 

答案 3 :(得分:1)

SGIMSDNGNU文档中,stack不提供迭代器。

答案 4 :(得分:0)

您在问

  

std :: stack是否公开迭代器?

许多人给出了答案。如果我的英语会更好,也许我也会理解“暴露”的确切含义。

如果我们指的是STL和类std :: stack以及此处定义的预定义函数,则答案为否。

我的猜测是您要询问,因为您想要迭代器。

因此,如果进一步走下去,我们将具有函数top()。并且top()可以解释为解引用的迭代器。这样,我们可以轻松定义迭代器以堆叠元素。保证堆栈的内存是连续的。

请参阅下文。我们正在为std :: copy:

定义并使用迭代器
#include <vector>
#include <stack>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <sstream>

using Number = int;
using UnderlyingContainer = std::vector<Number>;
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<Number>(testData),std::istream_iterator<Number>()} };

    // 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<Number>(std::cout, "\n"));
    return 0;
}

因此,您可以为堆栈创建迭代器。但是,请注意:

std :: stack故意将其元素隐藏在引擎盖下。因此,如果您对数据进行写访问,我将其视为设计错误。对我来说,通过const指针/迭代器进行读取访问是可以的。但是也许您最好使用std :: vector。 。