我有哈希表,我用2D向量实现

std::vector<std::vector<std::string> > htable;


另外,我在myiterator类(它是哈希表的子类)中编写了++,-和*运算符。

class myiterator{
    public:
        myiterator();
        myiterator(std::vector<std::vector<std::string> >& v, int ii, int jj) :
            vec(v), i(ii), j(jj) {}
        std::string operator*(){
            return vec[i][j];
        }
        myiterator& operator++(){
            if(j==vec[i].size()-1){
                int start=0;
                while(vec[start].size()==0){
                    start++;
                }
                i=start;
                j=0;
            }
            else{
                j++;
            }
            return *this;
        }
        // myiterator operator++(int); // postfix operator
        myiterator& operator--(){
            if(j==0){
                int end=vec[i].size()-1;
                while(vec[end].size()==0){
                    end--;
                }
                i=end;
                j=vec[end].size()-1;
            }
            else{
                j--;
            }
            return *this;
        } // prefix operator
        // myiterator operator--(int); // postfix operator
        std::string* operator->();
    private:
        std::vector<std::vector<std::string> >& vec; // the vector we are iterating over
        int i; // the position in the vector (first dimension)
        int j; // the position in the vector (second dimension)
    };
    myiterator begin() {
        int start=0;
        while(htable[start].size()==0){
            start++;
        }
        return (myiterator(htable, start, 0));
    }
    myiterator end(){
        int end=htable.size()-1;
        while(htable[end].size()==0){
            end--;
        }
        return (myiterator(htable, end, htable[end].size()-1));
    }


问题是,我必须如何实现->运算符?那他怎么办?我用谷歌搜索,但我听不懂。对不起,如果我的问题是nooby和基本的。提前致谢。

最佳答案

到目前为止看起来不错。我会说

    std::string* operator->(){
        return &vec[i][j];
    }


关于operator->的奇怪之处在于,在调用用户定义的operator->之后,编译器将在返回的任何内容上再次调用operator->。因此,您的operator->应该返回您要访问的对象的地址。

07-24 09:36
查看更多