Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
[
[1,2],
[3],
[4,5,6]
]
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6]
.
1 class Vector2D {
2 public:
3 int height, nextRow, nextCol;
4 vector<vector<int> > vec;
5 Vector2D(vector<vector<int>>& vec2d) {
6 vec = vec2d;
7 height = vec.size();
8 nextRow = nextCol = 0;
9 }
10
11 int next() {
12 int res = vec[nextRow][nextCol++];
13 if (nextCol == vec[nextRow].size()) {
14 nextCol = 0;
15 nextRow++;
16 }
17 return res;
18 }
19
20 //skip empty sub arrays
21 bool hasNext() {
22 while (nextRow < vec.size() && nextCol == vec[nextRow].size()) {
23 nextCol = 0;
24 nextRow++;
25 }
26 return nextRow < vec.size();
27 }
28 };
29
30 /**
31 * Your Vector2D object will be instantiated and called as such:
32 * Vector2D i(vec2d);
33 * while (i.hasNext()) cout << i.next();
34 */