# 2 Short C++ solution

• //1. with positions of vectors

``````class Vector2D {
int row;
int col;
vector<vector<int>> data;

public:
Vector2D(vector<vector<int>>& vec2d) {
data = vec2d;
row = 0;
col = 0;
}

int next() {
return data[row][col++];
}

bool hasNext() {
while(row < data.size() && data[row].size() == col)
row++, col = 0;
return row < data.size();
}
};
``````

//2. with Iterator

``````class Vector2D {
vector<vector<int>> data;
vector<vector<int>>::iterator rowIter;
vector<int>::iterator colIter;

public:
Vector2D(vector<vector<int>>& vec2d) {
data = vec2d;
rowIter = data.begin();
if(rowIter != data.end())
colIter = rowIter->begin();
}

int next() {
int r = *colIter;
colIter++;
return r;
}

bool hasNext() {
while(rowIter != data.end() && colIter == rowIter->end()) {
rowIter++;
if(rowIter != data.end())
colIter = rowIter->begin();
}

return rowIter != data.end();
}
};``````

• Since you're copying all the data anyway, it would be easier to just copy it into something one-dimensional. And I think using iterators on a copy doesn't make much sense.

• Agreed. I should've check the post first. Thank you for your comment.

• While this answer is technically acceptable, it violates the principle of least surprise because it mutates the state of the iterator when clients call `hasNext`.

• No it doesn't.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.