fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void moveZeroes(vector<int>& nums) {
  5. int j = 0, n = nums.size();
  6. //move the non-zero elements to the front
  7. for(int i = 0; i < n; i++){
  8. if(nums[i] != 0){
  9. nums[j++] = nums[i];
  10. }
  11. }
  12. //fill the remaining right indices with zeros
  13. for(int i = j; i < n; i++){
  14. nums[i] = 0;
  15. }
  16. }
  17.  
  18. int main() {
  19. int myints[] = {10, 0, 30, 0, 50, 60, 0, 80};
  20. vector<int> v(myints, myints+8);
  21. moveZeroes(v);
  22. for(int i = 0; i < v.size(); i++){
  23. cout << v[i] << " ";
  24. }
  25. cout << endl;
  26. return 0;
  27. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
10 30 50 60 80 0 0 0