>I have been trying to get this for the past 2 weeks !!
Do you have any code after these two weeks?
>1)Delete all the occurunces of x;
Removing an item from an array is an involved procedure. You need to shift all items after it to fill in the hole . But in this case it makes more sense to shift all items before it because you're filling the unused items on the left with 0. The trick is to handle the shifting and zero fill at the same time:
#include <algorithm>
#include <cstddef>
#include <iostream>
using namespace std;
#define size(a) (sizeof a / sizeof *a)
int main()
{
int a[] = {1,2,3,1,2,3,1,2,3,1,2,3};
int x = 2;
for ( size_t i = 0; i < size ( a ); i++ ) {
if ( a[i] == x ) {
// Remove and shift
for ( size_t j = i; j > 0; j-- )
a[j] = a[j - 1];
// Zero fill
a[0] = 0;
}
}
copy ( a, a + size ( a ), ostream_iterator<int> ( cout, " " ) );
cout<< endl;
}
This solution can be optimized if the valid items cannot be 0. Then you can only shift until you find a 0 and fill in that hole, thus saving yourself part of an expensive operation:
#include <algorithm>
#include <cstddef>
#include <iostream>
using namespace std;
#define size(a) (sizeof a / sizeof *a)
int main()
{
int a[] = {1,2,3,1,2,3,1,2,3,1,2,3};
int x = 2;
for ( size_t i = 0; i < size ( a ); i++ ) {
if ( a[i] == x ) {
// Remove and shift
size_t j;
for ( j = i; j > 0 && a[j - 1] != 0; j-- )
a[j] = a[j - 1];
// Zero fill
a[j] = 0;
}
}
copy ( a, a + size ( a ), ostream_iterator<int> ( cout, " " ) );
cout<< endl;
}