ASCII
ASCII

Reputation: 1

Iterating through an array of an unknown size C++

I'm having trouble with a push-down stack! I have an array with a maximum size of 10. I allow the user to input numbers into the stack with push and remove them with pop. Depending on how many numbers there are in the array, I have to iterate through the stack, which won't always be at a length of 10. Let's say the stack has 5 numbers (the size of the array is 10) in it. I need to go iterate through the elements up through element 5, because everything past that isn't a number. How can I do this?

Upvotes: 0

Views: 782

Answers (2)

dsolimano
dsolimano

Reputation: 8996

Why don't you keep track of how many elements there are on the stack in your C++ class? When someone calls push, increment the count, and when someone calls pop, decrement the count.

Upvotes: 4

Joel Falcou
Joel Falcou

Reputation: 6357

Use std::vector as the underlying storage for your stack and use iterators begin(), end() to get the range of valid element in your vector.

Upvotes: 2

Related Questions