# Share my non-iterator c++ solution 20ms

• This is inspired by https://leetcode.com/discuss/58683/c-with-queue-compatible-with-k-vectors

We maintain a queue also. The purpose of queue is to always keep the next one. And the size of queue is fixed. The most advantage is that it is self explain. Of course there can be other solutions.

``````class Vector2D {
``````

public:
Vector2D(vector<vector<int>>& vec2d) {
vecP = vec2d;
for(int i=0; i<vecP.size(); i++){
for(int j=0; j<vecP[i].size(); j++){
queueSolution.push(make_pair(i,j));
return;
}
}
}

``````void move2Next(int x){
for (int i=x+1;i<vecP.size(); i++){
for(int j=0; j<vecP[i].size(); j++){
queueSolution.push(make_pair(i,j));
return;
}
}
}

int next() {
int x = queueSolution.front().first;
int y = queueSolution.front().second;
queueSolution.pop();
if(y<vecP[x].size()-1){
queueSolution.push(make_pair(x, y+1));
}
else{
move2Next(x);
}

return vecP[x][y];
}

bool hasNext() {
return !queueSolution.empty();
}
``````

private:
vector<vector<int>> vecP;
queue<pair<int, int>> queueSolution;
};

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