Doing Shifts In An Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Firoza R
    New Member
    • Oct 2010
    • 4

    Doing Shifts In An Array

    Note: I'm using jGrasp and writing C++
    I'm supposed to create a "remove" function based off of the following postcondition:

    "The current item has been removed from the sequence, and the item after this (if there is one) is now the new current item."

    I'm aware that one cannot simply remove an element from an array, leaving the position unoccupied, but is it possible to shift the elements in the array to the left in such a way that the succeeding element 'overwrites' the preceding element?

    For example, |1|2|3|4|... --> |1|2|4|..., where '4' replaces '3'
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Yes but it's extremely inefficient because of all the data copying.

    Any this is C++ you should be using STL containers not arrays. Normally I would say use a std::vector instead of an array but if you want to delete (or insert) in the middle of a sequence then you should use std::list.

    Comment

    • Firoza R
      New Member
      • Oct 2010
      • 4

      #3
      My instructor only wants us to use arrays though.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Well then I would use memcpy but I would guess your instructor wants you to use a for loop and just copy the entries down the array.

        Comment

        • Firoza R
          New Member
          • Oct 2010
          • 4

          #5
          I never used the memcpy function. :(

          There are three main functions of this assignment: insert, attach, and remove. I used while loops for both insert and attach but I'm not sure how I would use a loop in general for the remove function. I have the following code:

          Comment

          • Firoza R
            New Member
            • Oct 2010
            • 4

            #6
            This is what I have for the remove function:

            Comment

            • Banfa
              Recognized Expert Expert
              • Feb 2006
              • 9067

              #7
              the line setting data[used-1] to 0 needs to be outside and after the loop.

              Comment

              Working...