Domanda

I need to iterate trough the contents of the internal container, however the only method that allows me to access it is constant:

const _Container& _Get_container() const
    {   // get reference to container
    return (c);
    }

So I can only get const iterator from the internal vector's begin().Is there any way around this?

È stato utile?

Soluzione 2

No, there is no such way. The idea behind std::stack (and similar adaptors) is that you will only use the stack interface. And a generic stack only allows inspection of the top element.

So technically, you don't want a "stack," you want an "iterable stack." And the standard library does not provide a container/adaptor for that, so you'll have to resort to one of

  1. implementing your own

  2. using a plain container and maintaining the stack-like access manually


Side note: I really wish the adaptors actually provided iteration functionality; after all, they're only adaptors, so they are guaranteed to be backed by an appropriate container (or they could at least provide iteration as long as the backing container does). But it's not currently part of the standard.

Altri suggerimenti

You can use a const_iterator to iterate over elements just fine, you just can't modify them.

If you do want to modify the objects, there's no way to do it without invoking undefined behavior - modifying an object declared as const is illegal.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top