954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

remove item in array

Hello!

Say I have an array called BBag[3], how would I write a function void remove(int val) that removes an occurence of val in BBag?

thanks!

Hong

hongfan
Newbie Poster
6 posts since Jan 2006
Reputation Points: 10
Solved Threads: 0
 

Something Like This

#include<iostream>
#include<string>

using namespace std;
int main( )
{ 
	string x("12345");
	cout<<x<<endl;
	x.erase(3,1);
	cout<<x;
	return 0;
}
SpS
Posting Pro
599 posts since Aug 2005
Reputation Points: 70
Solved Threads: 32
 

>Something Like This
Right, and that helps the OP delete an element from an array, how?

>that removes an occurence of val in BBag?
Just the first occurance, or all of them? The general process is to find the item, then shift everything after the item over it to fill in the gap:

[1][2][3][4][5][6]

Delete 3:
[1][2][ ][4][5][6]

Shift:
[1][2][4][5][6][6]

Since the last item is duplicated, you need to remember to ignore it in any size calculations. So if the original array had a size of 6, the new array has a size of 5 and you don't access the duplicated item at the end.

The actual process doesn't include a delete step, it's just the shift step:

for ( i = 0; i < n; i++ ) {
  if ( a[i] == target )
    break;
}

while ( ++i < n )
  a[i - 1] = a[i];

--n;
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

#include<iostream>
#include<string>

using namespace std;
int main( )
{
string x("12345");
cout<<x<<endl;
x.erase(3,1);
cout<<x;
return 0;
}

Also the OP needs it 2 B an int not string. So that wud B wrong too.

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

do you know a program that will ask for a location and delete the item in that location?

jeyson
Newbie Poster
2 posts since Oct 2009
Reputation Points: 5
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You