1

I'm trying to delete all elements of an array that match a particular case. for example..

if(ar[i]==0)

delete all elements which are 0 in the array

print out the number of elements of the remaining array after deletion

what i tried:

if (ar[i]==0)

   {
       x++;
  }
   b=N-x;

   cout<<b<<endl;

this works only if i want to delete a single element every time and i can't figure out how to delete in my required case. Im assuming that i need to traverse the array and select All instances of the element found and delete All instances of occurrences. Instead of incrementing the 'x' variable only once for one occurence, is it possible to increment it a certain number of times for a certain number of occurrences?

edit(someone requested that i paste all of my code):

int N;
cin>>N;
int ar[N];

int i=0;
while (i<N) {

    cin>>ar[i];
    i++;

}//array was created and we looped through the array, inputting each element.


int a=0;
int b=N;
cout<<b; //this is for the first case (no element is deleted)
int x=0;

i=0;                //now we need to subtract every other element from the array from this selected element.
while (i<N) {

    if (a>ar[i]) {  //we selected the smallest element.
        a=ar[i];

        }

    i=0;
    while (i<N) {
        ar[i]=ar[i]-a;
        i++;
        //this is applied to every single element.
    }

    if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step.
    {
        x++;
    }
    b=N-x;

    cout<<b<<endl;

    i++;
}


    return 0; }

the entire question is found here: Cut-the-sticks

4
  • Sort the array and increment index till it found the same value . Commented Dec 29, 2015 at 8:24
  • 1
    Please paste all of you code Commented Dec 29, 2015 at 8:25
  • 1
    Look up the standard algorithm, std::remove_if(). Commented Dec 29, 2015 at 8:34
  • Seems to be a duplicate of stackoverflow.com/questions/18090184/…. Anyway, check out std::remove. Commented Dec 29, 2015 at 8:40

6 Answers 6

5

You could use the std::remove function.

I was going to write out an example to go with the link, but the example form the link is pretty much verbatim what I was going to post, so here's the example from the link:

// remove algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::remove

int main () {
    int myints[] = {10,20,30,30,20,10,10,20};      // 10 20 30 30 20 10 10 20

    // bounds of range:
    int* pbegin = myints;                          // ^
    int* pend = myints+sizeof(myints)/sizeof(int); // ^                       ^

    pend = std::remove (pbegin, pend, 20);         // 10 30 30 10 10 ?  ?  ?
                                                   // ^              ^
    std::cout << "range contains:";
    for (int* p=pbegin; p!=pend; ++p)
        std::cout << ' ' << *p;
    std::cout << '\n';

    return 0;
}

Strictly speaking, the posted example code could be optimized to not need the pointers (especially if you're using any standard container types like a std::vector), and there's also the std::remove_if function which allows for additional parameters to be passed for more complex predicate logic.

To that however, you made mention of the Cut the sticks challenge, which I don't believe you actually need to make use of any remove functions (beyond normal container/array remove functionality). Instead, you could use something like the following code to 'cut' and 'remove' according to the conditions set in the challenge (i.e. cut X from stick, then remove if < 0 and print how many cuts made on each pass):

#include <iostream>
#include <vector>

int main () {
    // this is just here to push some numbers on the vector (non-C++11)
    int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
    int arsz = sizeof(arr) / sizeof(int);
    std::vector<int> vals;
    for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
    std::vector<int>::iterator beg = vals.begin();
    unsigned int cut_len = 2;
    unsigned int cut = 0;
    std::cout << cut_len << std::endl;
    while (vals.size() > 0) {
        cut = 0;
        beg = vals.begin();
        while (beg != vals.end()) {
            *beg -= cut_len;
            if (*beg <= 0) {
                vals.erase(beg--);
                ++cut;
            }
            ++beg;
        }
        std::cout << cut << std::endl;
    }
    return 0;
}

Hope that can help.

Sign up to request clarification or add additional context in comments.

1 Comment

Pbegin snd pend are unnecessary. std::begin and std::end work on c-arrays and are the recommendet way to specify the start and end of a range in c++. Also, maybe you could mention remove_if, which allows more complex conditions.
0

If you have no space bound try something like that,

  1. lets array is A and number is number.
  2. create a new array B
  3. traverse full A and add element A[i] to B[j] only if A[i] != number
  4. assign B to A

Now A have no number element and valid size is j.

Comments

0

Check this:

#define N 5

int main()
{
    int ar[N] = {0,1,2,1,0};
    int tar[N];
    int keyEle = 0;

    int newN = 0;
    for(int i=0;i<N;i++){
        if (ar[i] != keyEle) {
            tar[newN] = ar[i];
            newN++;
        }
    }

    cout<<"Elements after deleteing key element 0: ";
    for(int i=0;i<newN;i++){
        ar[i] = tar[i];
        cout << ar[i]<<"\t" ;
    }

}

Comments

0

Unless there is a need to use ordinary int arrays, I'd suggest using either a std::vector or std::array, then using std::remove_if. See similar.

untested example (with c++11 lambda):

#include <algorithm>
#include <vector>
// ...
std::vector<int> arr; 
// populate array somehow
arr.erase(
  std::remove_if(arr.begin(), arr.end()
     ,[](int x){ return (x == 0); } )
  , arr.end());

1 Comment

While I agree using a standard container is useful, the standard std::remove() or std::remove_if() algorithms work with "ordinary" arrays too.
0

Solution to Cut the sticks problem:

#include <climits>
#include <iostream>
#include <vector>

using namespace std;

// Cuts the sticks by size of stick with minimum length.
void cut(vector<int> &arr) {

    // Calculate length of smallest stick.
    int min_length = INT_MAX;
    for (size_t i = 0; i < arr.size(); i++)
    {
        if (min_length > arr[i])
            min_length = arr[i];
    }

    // source_i: Index of stick in existing vector.
    // target_i: Index of same stick in new vector.
    size_t target_i = 0;
    for (size_t source_i = 0; source_i < arr.size(); source_i++)
    {
        arr[source_i] -= min_length;
        if (arr[source_i] > 0)
            arr[target_i++] = arr[source_i];
    }

    // Remove superfluous elements from the vector.
    arr.resize(target_i);
}

int main() {
    // Read the input.
    int n;
    cin >> n;
    vector<int> arr(n);
    for (int arr_i = 0; arr_i < n; arr_i++) {
       cin >> arr[arr_i];
    }

    // Loop until vector is non-empty.
    do {
        cout << arr.size() << endl;
        cut(arr);
    } while (!arr.empty());

    return 0;
}

Comments

0

With a single loop:

if(condition)

{

for(loop through array)

   {
      if(array[i] == 0)
         {
            array[i] = array[i+1]; // Check if array[i+1] is not 0
            print (array[i]);
         }
      else
         {
            print (array[i]);
         }
 }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.