[Locked] Flatten 2D Vector
Problem Description:
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].
代码:
class Iterator { private: int i, j; vector<vector<int> > v; public: Iterator(vector<vector<int> > &vv) { i = j = 0; copy(vv.begin(), vv.end(), v.begin()); } bool hasNext() { return i < v.size(); } int next() { int nextVal = v[i][j]; if(++j == v[i].size()) { j = 0; ++i; } return nextVal; } };