Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::stack expose iterators?

Tags:

c++

stack

stl

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

like image 834
mdm Avatar asked Feb 08 '09 07:02

mdm


People also ask

Can I use iterator on stack in C++?

Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc).

Is the std::stack a data container?

std::stack > class stack; The std::stack class is a container adaptor that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure. The class template acts as a wrapper to the underlying container - only a specific set of functions is provided.

Why does stack :: top return a reference?

std::stack::top Returns a reference to the top element in the stack . Since stacks are last-in first-out containers, the top element is the last element inserted into the stack. This member function effectively calls member back of the underlying container object.


2 Answers

Stack does not have iterators, by definition of stack. If you need stack with iterators, you'll need to implement it yourself on top of other container (std::list, std::vector, etc). Stack doc is here.

P.S. According to a comment i got from Iraimbilanja, std::stack by default uses std::deque for implementation.

like image 86
Drakosha Avatar answered Oct 19 '22 20:10

Drakosha


If you need a stack with iterators, you have two choices:

  • std::vector using push_back(), pop_back().

  • std::deque with either push_back()/pop_back() or push_front()/pop_front().

like image 36
paxos1977 Avatar answered Oct 19 '22 21:10

paxos1977