我的哈希表有二维 vector
std::vector<std::vector<std::string> > htable;
和迭代器类。
class myiterator{
public:
myiterator();
myiterator(std::vector<std::vector<std::string> >& v, int ii, int jj) :
vec(v), i(ii), j(jj) {}
myiterator& operator++(); // prefix operator
myiterator& operator--(); // prefix 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));
}
我已经为迭代器实现了开始和结束,但我不知道如何以及如何处理前缀运算符。另外,我无法用谷歌搜索运算符“->”是什么? 那么,你能给我一些关于二维 vector 的实现前缀迭代器的小技巧或文章吗?提前致谢。
最佳答案
operator->
是一个解引用运算符。它允许您编写 it->myFunc()
(即允许迭代器像指针一样运行)。通常,您将返回迭代器指向的类型。
您的前缀运算符(operator++
和 operator--
)应该分别将迭代器移动到下一个和上一个元素。
作为旁注,如果您正在重载 operator->
,您也应该重载 operator*()
,并且您可能还想重载后置 -修复运算符 myiterator operator--(int)
和 myiterator operator++(int)
。
关于c++ - 前缀运算符的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19893961/