繁体   English   中英

使用正向迭代器进行反向迭代

[英]Reverse iterate using forward iterator

我有一个功能,可以将集合中的每个元素与以前的元素进行比较。 我想做这样的事情:

    std::set<int> sSet;
    std::set<int>::iterator it;
    std::set<int>::iterator itR;

    sSet.insert(1);
    sSet.insert(2);
    sSet.insert(3);
    sSet.insert(4);
    sSet.insert(5);
    sSet.insert(6);

    for (it=sSet.begin(); it!=sSet.end(); ++it)  //simple forward loop
    {
      itR = it;
      if(it != sSet.begin())  
        itR--;
      for(;itR!=sSet.begin();itR--)
      {
        //Reverse iteration
        //for comparing every element to all the previous elements
        //Problem here is it goes up to the second element only and not first 
        //because of the condition itR!=sSet.begin()
      } 
    }     

我当时在考虑使用反向迭代器,但同样找不到从特定位置(或正向迭代器)设置反向迭代器的方法。

有什么正确的方法吗?

更新 :上面使用的集仅用于演示。 作为一组类的实际实现,定义如下:

    std::set<TBigClass, TBigClassComparer> sSet;
    class TBigClassComparer
    {
     public:
     bool operator()(const TBigClass s1, const TBigClass s2) const
     {
       //comparison logic goes here
     }
    };

要反向吗? 使用反向迭代器:

std::set<int> sSet;
    std::set<int>::iterator it;
    std::reverse_iterator<std::set<int>::iterator> itR;

sSet.insert(1);
sSet.insert(2);
sSet.insert(3);
sSet.insert(4);
sSet.insert(5);
sSet.insert(6);

for (it=sSet.begin(); it!=sSet.rend(); ++it)  //simple forward loop
{
  itR = std::reverse_iterator<std::set<int>::iterator>(it);
  for(;itR!=sSet.rbegin();++itR)
  {
    //Reverse iteration
    //for comparing every element to all the previous elements
    //Problem here is it goes up to the second element only and not first 
    //because of the condition itR!=sSet.begin()
  } 
}     

但是请注意,当迭代器反向时,反向版本并不指向范围中的同一元素,而是指向其之前的元素。 如此,为了安排范围的past-the-end元素:指向范围中的end-the-end元素的迭代器,当反转时,将更改为指向最后一个元素(而不是过去) )(如果取反,它将是范围的第一个元素)。 而且,如果反转范围中第一个元素的迭代器,则反转的迭代器指向第一个元素之前的元素(如果反转,则是范围的末尾元素)。

您可以使用内部的while循环:

while (true)
{
    // do your comparison here

    if (itR == sSet.begin())
        break;

    --itR;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM