array issue

Hi guys
I have a code written

output array
Int b[] = {0,0,0,0,0,8,9,1,5,2,7,2}



input array
int a[] = {0,8,9,0,0,1,5,2,0,7,2,0};


int main()
{
int n = sizeof(a)/sizeof(int);

for(int i =0;i<=n;i++)
{
for(int j =i+1;j<=n;j++)
{
if(a[i]!=0 && a[j]>=0)
{
int temp;
temp =a[i];
a[i]=a[j];
a[j]=temp;

}
}
}

for(int z=0;z<=n;z++)
{
std::cout<<a[z]<<endl;
}
return 0;
}
C/C++ array index start from 0.

1
2
3
4
5
6
7
8
for(int i =0;i<n;i++)
...

for(int j =i+1;j<n;j++)
...

for(int z=0;z<n;z++)
...
Last edited on
My question was to shift all the zeroes in the array
int a[] = {0,8,9,0,0,1,5,2,0,7,2,0};

to the left , the output should be
Int b[] = {0,0,0,0,0,8,9,1,5,2,7,2}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <iterator>
#include <algorithm>

bool isZero(int i) { return (i==0) ? true : false; }

int a[] = {0,8,9,0,0,1,5,2,0,7,2,0};

int main()
{
  int n = sizeof(a)/sizeof(int);
  stable_partition(a, a+n, isZero);
  copy(a, a+n, ostream_iterator<int>(cout,"\n"));
}
++sohguanh! I have never used that algorithm before. Nice example.
I try as much as possible to use Standard C++ STL. Refer to http://www.cplusplus.com/reference/algorithm/ for all of them.

Don't re-invent. Practise re-use, re-use and more re-use. Only craft your own when you cannot find them even in the Boost library!
Topic archived. No new replies allowed.