[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;
    }
};

 

posted @ 2016-02-26 20:45  CarlGoodman  阅读(113)  评论(0编辑  收藏  举报