How to remove first element from int array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DD2783
    New Member
    • Nov 2012
    • 1

    How to remove first element from int array

    I'm currently trying to remove the first element in an int array using objects in C#. I have just coded how to add an element to that start of the array and though it was just a case of changing a few things.

    Here's the code for the addFirst() but i can't for the life of me figure out removeFirst()

    Code:
            public void addFirst(int value)
            {
                if (isFull())
                {
                    throw new Exception("List full");
                }
                else
                {
                    for (int pos = size;pos > 0; pos-- )
                    {
                        values[pos] = values[pos - 1];
                    }             
                    values[0] = value;
                    size++;
                }
            }
    Last edited by Rabbit; Nov 14 '12, 06:39 PM. Reason: Please use code tags when posting code.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    What you need to do is move the value of the next cell into the current cell and then decrement the size of the array by 1.

    Comment

    • PsychoCoder
      Recognized Expert Contributor
      • Jul 2010
      • 465

      #3
      You have a couple options, you could use the RemoteAt Method of the List<T>, that's your simple option, which would work like this:


      Code:
      List<int> list = new List<int>(){ 1, 2, 3, 4, 5, 6 };
      list.RemoveAt(1);

      Would remove the first element in the array.

      If, however, you're forced to use arrays you could write an extension method like this one:

      Code:
      public static T[] RemoveAt<T>(this T[] source, int idx)
      {
          T[] destination = new T[source.Length - 1];
          if( idx > 0 )
              Array.Copy(source, 0, destination, 0, idx);
      
          if( idx < source.Length - 1 )
              Array.Copy(source, idx + 1, destination, idx, source.Length - idx - 1);
      
          return destination;
      }
      Which could be used like above:

      Code:
      int[] array = new int[4] {2, 4, 6, 8};
      array.RemoveAt(1);
      Hope that helps :)

      Comment

      Working...