0 5 0 7 6 3
5 7 6 3 0 0
0 5 0 7 6 3
p1p2
0 5 0 7 6 3 // Compare
p1 p2
5 0 0 7 6 3 // Swap
p1 p2
5 0 0 7 6 3 // Move
p1p2
5 0 0 7 6 3
p1p2
5 0 0 7 6 3
p1 p2
5 0 0 7 6 3
p1 p2
5 7 0 0 6 3
p1 p2
5 7 0 0 6 3
p1 p2
#include <iostream>
#include <vector>
#include <algorithm>
void moveZeros(std::vector<int> &v)
{
auto iter1 = v.begin();
for (auto iter2 = v.begin(); iter2 != v.end(); ++iter2)
{
if (*iter2 != 0)
{
std::iter_swap(iter1, iter2);
++iter1;
}
}
}
int main()
{
std::vector<int> v = {0, 5, 0, 7, 6, 3};
moveZeros(v);
for (int e : v)
std::cout << e << std::endl;
return 0;
}
5
7
6
3
0
0