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

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;
}

>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;
Member Avatar for iamthwee
#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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.