My program should replace the group with an even number of zeros, which go in a row, with two zeros and group with an odd number of zeros replace with only one zero. If the input has no zeroes, it should be left as is. I've written following code to solve this problem.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cout << "Enter an array size:\n";
cout << "n = ";
cin >> n;
vector<int> arr(n);
vector<int> temp_arr(n);
cout << "Enter an array:\n";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
for (int i = arr.size() - 1; i >= 1; i--) {
if (arr[i] == arr[i - 1] && arr[i] == 0){
temp_arr.push_back(i);
}
else if (arr[i] != 0) {
if (temp_arr.size() % 2 == 1) {
arr.erase(arr.begin() + i);
temp_arr.clear();
}
else if (temp_arr.size() % 2 == 0){
arr.erase(arr.begin() + i);
arr.insert(arr.begin() + i , 0);
temp_arr.clear();
}
}
}
cout << "Output of the program:\n";
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
system("pause");
return 0;
}
But after compilation I've got this:

The whole array was replaced with zeros.
What did I do wrong?