Array problem

Discussion in 'C' started by chadr6, Jan 23, 2007.

  1. chadr6

    chadr6 New Member

    Joined:
    Jan 23, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    BC, Canada
    What I need to do is implement a function with the prototype:

    void squeeze(int arr[], int& size, int val);

    The function has to remove all occurrences of val from arr and update size accordingly. I am quite new to C++ and am not able to figure out how to do this. Does anyone have any ideas?

    Thanks
     
  2. chadr6

    chadr6 New Member

    Joined:
    Jan 23, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    BC, Canada
    I forgot to mention that this has to be done in C++
     
  3. DaWei

    DaWei New Member

    Joined:
    Dec 6, 2006
    Messages:
    835
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Semi-retired EE
    Location:
    Texan now in Central NY
    Home Page:
    http://www.daweidesigns.com
    You can't resize an ordinary array unless it has been created on the heap. If you reallocate it, you have to be prepared to update the pointer to its (possibly new) location, and remember to free it. You can, of course, remove unwanted values and modify the size variable. That won't actually resize the array, and you can't lengthen it.

    To do that, you would begin at the beginning, find the first value to be tossed, copy all elements from the next to the end of the array from that location onward, begin from there, wash, rinse, and repeat until done. It would require a little more code to zero-out from the new end to the old end.

    Since you're using C++, I would recommend a vector (from the STL). This is a class with array features, much like a string-class string.

    If you want to do it either way, toss some code here and ask about any problems you may have.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice