Jump to content
Can't remember your login details? Read more... ×
freakonaleash

c++ remove an item from an array

Recommended Posts

Hey all

 

im trying to remove and item from an array but i want to shift all the items as well. for eg:

 

Array

| 1 | 2 | 3 | 4 | 5 |

delet element 2

|1 | 3 | 4 | 5 | |

 

Some things though:

1. my array is predefined to being 100 items,

2. only some of the array will be populated. I have a variable that records how many elements are in use

3. i need to write the result out to a text file but i dont want to have any blank lines

 

Thanks

Stephen

Share this post


Link to post
Share on other sites

sounds good. did you have a question? maybe some code thus far?

Share this post


Link to post
Share on other sites

Well i got the code that reads the information into the array, and i can output that array again on screen. the next thing is to be able to specify an item to delete.

So far i got rought statements but nothing definated:

 

//Recieve the word to be deleted
cin >> delete_me
//find the placement of the word in the array
for (i = 0; i <= array_size; i ++)
{
	if (array[i] == delete_me) item_to_delete = i
	else cout << "Unable to find the item to delete"  //go back to main menu
}

So from this i have found the elements number that i want to delete, now is where my brain start to grind to a halt. I know i would need to "remove" the item at array[item_to_delete] but im a little unsure on how to do it from here:

my two options so far:

1 . create a new array and transfer all the items to it, excluding the item to be deleted, but im not sure if its too messy (this is only thinking code btw, not tested yet). Then write the temp array to the text file.

for (i=0; i<=array_size - 1; i++)
{
	  if (i==item_to_delete) i++;
	else
	{
	for (j=0; j <= array_size -1; j++)
	{
		temp_array[j] = array[i];
	}
	}
}
2. write all the element to the text file except the one i want to delete. need to test as i dont want to have any spare lines

for (i=0; i<= array_size-1; i++)
{
	if (i==item_to_delete) i++;
	else fout << array[i];
}

im liking the second one though as the code seems cleaner but im not sure if that "if" statement will be the correct way to "remove" that array item. Also, all this code was just knocked up in my head. there was no testing done on it yet as im at work and havent got the program with me. there may be syntax errors and such.

Edited by freakonaleash

Share this post


Link to post
Share on other sites

split the array at the element you want to remove, then rejoin minus that element

 

eg remove el 4

 

1|2|3|4|5|6|7|8|9|0

 

becomes

 

1|2|3|4

5|6|7|8|9|0

 

chop off last element of ar1

 

1|2|3

5|6|7|8|9|0

 

then join

1|2|3|5|6|7|8|9|0

 

alternatively, dont actually delete the element, but set it to null (or some token)

write a wrapper class that ignores all null entries(or token entries)

or dont write a wrapper class, and just keep track of all those nulls manually

 

 

or another method

from point you want to delete (call it x), shift all elements left one spot

 

n = x

for.... until n == {guess what goes here}

>arr[n] = arr[n+1]

{you finish the rest}

 

or another method,

make a new array of size(initial_array)-1

loop thru initial_array keeping a counter

if counter == item_to_remove skip,

else put current element in to next spot in the array

 

(hint: you will need to keep 2 counters for this to work)

(hint 2: incorporate this into your 'find the element to delete' array)

(hint 3: do your own homework ;) programming is more about solving problems than it is writing them out :P)

 

 

 

 

there are heaps of ways to do it, some are shit, some are better, some suit different purposes, I've intentionally given you some shit methods

Edited by clockworkman

Share this post


Link to post
Share on other sites

thanks for that. Agree with hint3. I've done a lot of reading on diffirent options but i always like also asking on atomic as there are some smark cookies on here :)

Share this post


Link to post
Share on other sites

Assuming you know you'll never have more than 100 items, I think the cleanest way is to make a new array and transfer everything (except the element you don't want) across. Otherwise I personally would make a linked list.

Share this post


Link to post
Share on other sites

thanks. The lecturer would "perfer" us to use arrays from what i read. I have put in a limit when reading the dta into the array that stops after it is filled to prevent issues.

Share this post


Link to post
Share on other sites

First year info tech or comp sci?

 

Soon you'll be looking at STL containers in C++ which will have implementations of these things so you don't have to worry about it, but in the mean time, it's worthwhile knowing how containers, (e.g., arrays, stacks, linked lists), in their many forms work.

 

For what you're trying to do, I'd simply overwrite whatever data is in the element you want to delete, with the next element, and keep doing this until you're at the end of the array.

 

Here's a code snippet:

 

for (int i = 0; i < array_size; i++) // Loop to find the item to delete.
{
  if (array[i] == item_to_delete) // If we find the item to delete...
  {
	for (int j = i; j < array_size - 1; j++) // Iterate through the remaining elements, stopping one before the end.
	{
	  array[j] = array[j + 1]; // Overwrite the current element with the next. This effectively deletes the item to delete, and moves everything else down one.
	}
	array[array_size - 1] = NULL; // Set the last item in the array to null, (or some other appropriate null value). This may not necessarily be needed, but is good practice.
	array_size--; // Reduce the array size by one.
	break; // Exit out of the 'find item to delete' loop.	
  }
}

This is always going to be O(n) because you are always iterating through every element in the container, (array); but you'll learn more about big O more later, (oh and maybe something about mathematical notation too).

 

You could do all sorts of things like resize a dynamic array on add/delete etc., use a linked list instead to improve efficiency, quick sort the array then use a smart searching algorithm... but realistically, this is the place for you to start.

Edited by Periander

Share this post


Link to post
Share on other sites

Is the array sorted? if so - binary chop to the delete element (order log n vs order n to find the delete element)

 

Now I'm an old school C programmer - never stepped into C++, so out of interest...

 

Is the numeric data being stored as int or char or strings? If characters or strings - well string handling and string.h are your friends! Find the delete point using memchr or strrchr or strstr and if non null (match found) delete and copy a single entire string shift (memmove or strncpy), not a step by step move everything down one.

 

The entire search and replace code (above) would look like something like...

 

#include <string.h>
#include <stdio.h>

#define A_SIZE 100

char array[A_SIZE], *find, item_to_delete[A_SIZE];

main()
{

   fprintf(stderr,"Enter the items you want mainpulated\n");	 /* I write to stderr which is unbuffered so I don't have to issue a fflush(stdout) */
   gets(array);						  /* initialise your array of items */

   fprintf(stderr,"Enter the item you wish to delete:  ");			
   gets(item_to_delete);								

/* The arrays are now populated and NULL terminated */

	if ((find = strstr( array, item_to_delete )) != NULL)	   /* determine if the item is in the array to start with */
	  strncpy( find, find+ strlen(item_to_delete),  A_SIZE - (int)(find - array) - strlen(item_to_delete));		/* shift the tail of the array past this item */
  
	fprint( stderr, "\n Removing this entry leaves %s\n", array);									
}
Edited by g__day

Share this post


Link to post
Share on other sites

The thing is though, the point of these exercises, (as mentioned by a few above), is to teach the underlying basics of how containers work.

 

These basics apply to all languages, but many have their own container types with niceties such as sorting and finding and deleting and adding all optimised and abstracted away from you.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×