C++ solutions, Using only iterators and without any iterators

• Solution 1: Without iterators

``````class Vector2D {
private:
vector<vector<int>> vec;
int row;
int col;
public:
//Constructor
Vector2D(vector<vector<int>>& vec2d) {
vec = vec2d;
row = 0;
col = 0;
}

int next() {
//Save the value and move to next column
int val = vec[row][col];
++col;
return val;
}

bool hasNext() {
//Move to a non empty row
while (row < vec.size() && vec[row].size() == col) {
++row;
col = 0;
}
return row < vec.size() && col < vec[row].size();
}
};
``````

Solution 2: Using C++ iterators only (NOT using vector size or indexing)

``````class Vector2D {
private:
vector<vector<int>>::iterator vec2dStart, vec2dEnd;
vector<int>::iterator vecStart;
public:
Vector2D(vector<vector<int>>& vec2d) {
vec2dStart = vec2d.begin();
vec2dEnd = vec2d.end();
vecStart = (*vec2dStart).begin();
}

int next() {
int val = *vecStart;
++vecStart;
return val;
}

bool hasNext() {
//Move to a non empty row
while (vec2dStart != vec2dEnd && vecStart == (*vec2dStart).end()) {
++vec2dStart;
//If vec2dStart has reached vec2dEnd, it can not be de-referenced
if (vec2dStart != vec2dEnd) {
vecStart = (*vec2dStart).begin();
}
}

return vec2dStart != vec2dEnd;
}
};
``````

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