2 Short C++ solution


  • 6
    J

    //1. with positions of vectors

    class Vector2D {
       int row;
       int col;
       vector<vector<int>> data;
    
    public:
       Vector2D(vector<vector<int>>& vec2d) {
           data = vec2d;
           row = 0;
           col = 0;
       }
    
       int next() {
           return data[row][col++];
       }
    
       bool hasNext() {
           while(row < data.size() && data[row].size() == col)
               row++, col = 0;
           return row < data.size();
       }
    };
    

    //2. with Iterator

    class Vector2D {
       vector<vector<int>> data;
       vector<vector<int>>::iterator rowIter;
       vector<int>::iterator colIter;
    
    public:
       Vector2D(vector<vector<int>>& vec2d) {
           data = vec2d;
           rowIter = data.begin();
           if(rowIter != data.end())
               colIter = rowIter->begin();
       }
    
       int next() {
           int r = *colIter;
           colIter++;
           return r;
       }
    
       bool hasNext() {
           while(rowIter != data.end() && colIter == rowIter->end()) {
               rowIter++;
               if(rowIter != data.end())
                    colIter = rowIter->begin();
           }
        
           return rowIter != data.end();
       }
     };

  • 4

    Since you're copying all the data anyway, it would be easier to just copy it into something one-dimensional. And I think using iterators on a copy doesn't make much sense.


  • 0
    J

    Agreed. I should've check the post first. Thank you for your comment.


  • 0
    P

    While this answer is technically acceptable, it violates the principle of least surprise because it mutates the state of the iterator when clients call hasNext.


  • 0

    No it doesn't.


Log in to reply
 

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