Removing elements from vectors without erasing

I'm writing an inventory program that catalogs items based on quantity, price, ID number, etc. I need to create a function that removes an item from the inventory vector based on an ID number. Problem is, I'm not allowed to use the vector erase function. What other methods can I use?
Last edited on
- find index of item to be removed
- left-shift all items beyond that index by 1 (use a loop)
- inventory.resize(inventory.size() - 1);

There's other ways, too.. e.g. copy all items except the item-to-erase into a new vector, then re-assign to the original vector.
Last edited on
quantity, price, ID number, etc.

Does the "remove" mean "reduce quantity" or really "remove element"?

The http://www.cplusplus.com/reference/vector/vector/ has four members that reduce number of elements.
you can also add a "I AM DELETED" boolean to your object, and adjust your iteration to ignore those marked records. Lazy deletion is often cleaned up once in a while, which puts you back where you were (needing to remove them for real) if the vector gets too big with too much deleted junk in it, but at least you can stable-sort off this field to move all the deleted ones to the back (so you only need to iterate until you find ONE deleted item, after that, all are, if you keep it sorted). There are pros and cons to doing this, but its 'one way' to do it. You can also have new items replace a deleted one (if any) before adding space to the container, so it may self correct if the adds and deletes are roughly about the same in quantity.

take note: vectors are not the best container if you want to constantly resize them with adds and deletes.

--stable sort keeps the order of the unmarked items intact.
-- normal sort may reorder the unmarked items, but is faster.
Last edited on
Does the order of the stored items have to remain the same? If they don't, then when you find the position of the item to be deleted, swap it with the last item (if not last) and reduce the size count by 1.
Topic archived. No new replies allowed.