adding iterator exercise

This commit is contained in:
Jidong Xiao
2023-09-29 10:48:17 -04:00
parent d41f5870d4
commit 927fa8cb04
2 changed files with 22 additions and 1 deletions

View File

@@ -0,0 +1,21 @@
class Solution {
public:
void moveZeroes(vector<int>& nums) {
vector<int>::iterator itr = nums.begin();
// use itr2 to represent the "new" vector
vector<int>::iterator itr2 = nums.begin();
while(itr != nums.end()){
// traverse the vector and store all non-zero elements in the "new" vector.
if(*itr != 0){
*itr2 = *itr;
itr2++;
}
itr++;
}
// as we skipped zeroes above, we now fill them in.
while(itr2!=nums.end()){
*itr2 = 0;
itr2++;
}
}
};