0

I have to create an iterator to the stack but before pushing some values into the stack, after struggling for some time I figured out why following chunk of code causes seg fault

#include <map>
#include <set>
#include <stack>
#include <utility>
#include <algorithm>

typedef std::stack<std::pair<short, std::set<short>>> stack_t;

int main()
{
    std::set<short> x = {0, 1, 2, 3};

    stack_t my_stack;
    auto iter = my_stack.top(); // error (segmentation fault)

    my_stack.push(std::make_pair(3, x));
    iter = my_stack.top();
    //...

    return 0;
}

is there a way to create an iterator before initializing the stack?

codekiddy
  • 5,897
  • 9
  • 50
  • 80
  • http://stackoverflow.com/questions/525365/does-stdstack-expose-iterators – dragosht Jul 30 '14 at 11:02
  • 1
    `std::stack` doesn't have iterators. The underlying container does, but there's no public way to access it. What exactly are you trying to do with it? – T.C. Jul 30 '14 at 11:05
  • I have about 20 or so stacks which are accesses withing separate scope each, so I wanted to create one global iterator and use it withing scopes to access these stacks. instead of crating 20 new variables.. – codekiddy Jul 30 '14 at 11:07

2 Answers2

1

There is no way to get iterators to a stack - it would be against the very purpose of the stack, where you can access only the top element. When you try to

auto iter = my_stack.top();

you do not get the iterator but the element on the top. In your example you try it with an empty stack, hence the error.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
1

Top doesn't return an iterator, but the top element, although the stack is empty, which causes the error. Stack does not support iterators. It is not a fully-fledged container, but a container adapter, which is like a special typedef for an underlying container, the default of which is deque.

Be aware that certain operations, which depend on the data structure, may invalidate existing iterators. What do you intend to do with your iterator?

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91