c++ custom iterator solution


  • 0
    B
      bool searchMatrix(vector<vector<int>> &matrix, int target) {
            struct {
                vector<vector<int>> &m;
    
                struct searchiterator : public iterator<forward_iterator_tag, int> {
                    searchiterator(const vector<std::vector<int>>::iterator &itCol, const vector<int>::iterator &itRow)
                            : itCol(
                            itCol), itRow(itRow) {}
    
                    vector<vector<int>>::iterator itCol;
                    vector<int>::iterator itRow;
    
                    searchiterator &operator++() {
                        if (itCol->end() == itRow + 1) {
                            itCol++;
                            itRow = itCol->begin();
                        } else itRow++;
                        return *this;
                    }
    
                    bool operator==(const searchiterator &rhs) const {
                        return std::tie(itCol, itRow) == std::tie(rhs.itCol, rhs.itRow);
                    }
    
                    bool operator!=(const searchiterator &rhs) const {
                        return !(rhs == *this);
                    }
    
                    int &operator*() { return *itRow; }
                };
    
                searchiterator begin() {
                    return searchiterator {m.begin(), m.begin()->begin()};
                }
    
                searchiterator end() {
                    return searchiterator {m.end(), m.end()->begin()};
                }
            } search{matrix};
            return binary_search(search.begin(), search.end(), target);
        }
    

    probably overkill.


Log in to reply
 

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