#include<iostream>
#include<vector>
using namespace std;
int n;
vector<int> CompactIntegers(vector<int> nums,int &n)
{
vector<int> out;
int i = 0;
while(i<nums.size())
{
if (nums[i] == 0)
{
i++;
--n;
}
else
{
out.push_back(nums[i]);
++i;
}
}
return out;
}
int main()
{
cin >> n;
int x;
vector<int> nums(n);
for (int i = 0; i < n; ++i)
{
cin >> x;
nums[i] = x;
}
vector<int> out;
out = CompactIntegers(nums, n);
for (int j = 0; j < n; ++j)
cout << out[j] << " ";
cout << endl;
cout << n;
return 0;
}
关于数组的输入:
用while(cin>>x)会进入死循环,用for循环限制输入个数即可解决