Skip to content

Instantly share code, notes, and snippets.

@zhuangh
Created April 16, 2018 05:33
Show Gist options
  • Save zhuangh/ca990c1b68355215f88597d4cef2f298 to your computer and use it in GitHub Desktop.
Save zhuangh/ca990c1b68355215f88597d4cef2f298 to your computer and use it in GitHub Desktop.
2d iterator with remove()
class Vector2D {
private:
vector<vector<int>>::iterator row, iBegin, iEnd;
vector<int>::iterator col;
public:
Vector2D(vector<vector<int>>& vec2d) {
iBegin = row = vec2d.begin();
iEnd = vec2d.end();
if(vec2d.size())
col = row->begin();
//remove();
//col++;
//col++;
/*
if(hasNext())
cout<<next()<<endl;
if(hasNext())
cout<<next()<<endl;
if(hasNext())
remove();
row = iBegin;
col = row->begin();
*/
}
int next() {
if(hasNext()){
int val = *col;
col++;
return val;
}
}
bool hasNext() {
while(row != iEnd && col == row->end()){
row++;
col = row->begin();
}
return row != iEnd;
}
bool remove(){
if(col == row->begin()){
auto pre = prev(row);
while(pre != iBegin && (*pre).empty()) pre = prev(pre);
//cout<<"remove sz"<<(*pre).size()<<endl;
if(!(*pre).empty()) {
cout<<"remove "<<*prev((*pre).end())<<endl;
(*pre).erase(prev((*pre).end()));
}
}
else{
(*row).erase(prev(col));
col--;
}
return true;
}
};
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i(vec2d);
* while (i.hasNext()) cout << i.next();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment