Implement an iterator to flatten a 2d vector.

Have you met this question in a real interview?

Yes

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 Vector2D {
public:
    Vector2D(vector<vector<int>>& vec2d) {
        // Initialize your data structure here
        begin =  vec2d.begin();
        end = vec2d.end();
        pos = 0;
    }

    int next() {
        // Write your code here
        return (*begin)[pos++];
    }

    bool hasNext() {
        // Write your code here
        while (begin != end && pos == (*begin).size()) {
            ++begin;
            pos = 0;
        }
        return begin != end;
    }

private:
    vector<vector<int>>::iterator begin, end;
    int pos;
};

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i(vec2d);
 * while (i.hasNext()) cout << i.next();
 */

results matching ""

    No results matching ""