Jump to content
  • Advertisement
Sign in to follow this  
kingpinzs

Need help with a array sequence

This topic is 2495 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is what I need to do

// void advance( )
// Precondition: is_item returns true.
// Postcondition: If the current item was already the last item in the
// sequence, then there is no longer any current item. Otherwise, the new
// current item is the item immediately after the original current item.

And this is what I did



void sequence::advance( )
{

if(is_item())
{

if(current_index <= used)
{
++current_index;
}
}


but it goes passed the actual array data.


How can I fix that?

I'm using c++

Share this post


Link to post
Share on other sites
Advertisement
Think through the algorithm in your head with very small numbers. Does it behave correctly when current_index is 0 and used is 1, prior to the call?

A face-palm should follow shortly.

Share this post


Link to post
Share on other sites
After thinking about it for a while I came up with this.





void sequence::advance( )
{

if(is_item())
{

if(current_index <= used-1)
{
++current_index;
}

}
}


but it is still advancing passed the array that has been created.

Share this post


Link to post
Share on other sites

Postcondition: If the current item was already the last item in the sequence, then there is no longer any current item
[/quote]
How do you plan to represent the highlighted condition? In the C++ standard library, this could typically be handled by a "one past the end" iterator - which sounds similar to the situation you are in. Another option is using a sentinel value like -1 for the current_index in this case.

The main design issue then is ensuring that such a non-existent element is not accessed - only tested for existence.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!