【问题标题】:Implementation of prefix operator前缀运算符的实现
【发布时间】:2013-11-10 19:17:07
【问题描述】:

我的哈希表有二维向量

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));
    }

我已经为迭代器实现了开始和结束,但我不知道如何以及如何处理前缀运算符。另外,我无法用谷歌搜索运算符“->”是什么? 所以,拜托,你能给我一些关于二维向量实现前缀迭代器的小技巧或文章吗?提前致谢。

【问题讨论】:

标签: c++ iterator


【解决方案1】:

operator-&gt; 是一个解引用运算符。它允许您编写it-&gt;myFunc()(也就是说,允许迭代器表现得像一个指针)。通常,您将返回迭代器指向的类型。

您的前缀运算符(operator++operator--)应将迭代器分别移动到下一个和上一个元素。

附带说明,如果要重载operator-&gt;,则还应重载operator*(),并且您可能还需要重载后缀运算符myiterator operator--(int)myiterator operator++(int)

【讨论】:

  • +1 注意:后者(后缀)运算符的实现确实返回对它们被触发的迭代器的引用。在这两种情况下,都会使用*this 修改的当前状态构造一个新的 by-val 结果迭代器。然后*this被更新(前进或后退),by-val temp是返回值,作为iteratornot作为iterator&amp;。这是后缀运算符比前缀更昂贵的主要原因,前缀只是前进/后退迭代器并将*this作为iterator&amp;返回。
  • 好点。添加了返回值来证明这一点。 :)
  • 对不起,我的问题很简单,但是 *this 是什么?
  • @ratkke 在语言意义上,它是您的对象的实例。对于我刚刚写的小说的描述,它是“迭代器对象”,您在其上触发操作符。
  • @WhozCraig 但是为什么我需要为我的解引用运算符实现后缀运算符?
【解决方案2】:

当你增加你的迭代器时,你基本上和你对 begin() 所做的一样。

if ( j == htable[i].size() - 1 )  // j is at the end of the inner vector
  // set j to zero
  // increment i until htable[i] is not the end of the outer vector and is not empty
else
  // increment j

另一方面,我建议使用向量的迭代器来代替 i 和 j。例如:

class MyIterator
{
  std::vector< std::vector< std::string > >::iterator i;
  std::vector< std::string >::iterator j;

  // ...
}

MyIterator begin()
{
  std::vector< std::vector< std::string > >::iterator o_iter = htable.begin();
  while ( o_iter != htable.end() && o_iter->empty() )
    ++o_iter;

  // assuming htable wasn't empty...
  return MyIterator( htable, o_iter, o_iter->begin() );
}

【讨论】:

  • “使用向量的迭代器”是什么意思。
  • 谢谢,但是你能解释一下这两行吗,'std::vector>::iterator o_iter = htable.begin();'和'return MyIterator(htable, o_iter, o_iter->begin());'我不明白你的想法。提前致谢
  • 使用整数可以正常工作,也许当您的项目完成后,您转换为使用向量的迭代器。 htable.begin() 将向量的迭代器返回到 htable 的开头。这只是另一种方式,我不会太担心。
猜你喜欢
  • 2011-05-19
  • 2011-03-12
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多