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

Reverse iterate using forward iterator

本文关键字:迭代 迭代器      更新时间:2023-10-16

我有一个功能,我想比较集合中的每个元素与前面的元素。我想这样做:

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

我想在这里使用反向迭代器,但是我又找不到从特定位置(或正向迭代器)设置反向迭代器的方法。

有正确的方法来做这件事吗?

Update:上面使用的设置只是为了演示。实际实现为类的集合,定义如下:

    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()
  } 
}     
但是,请注意,当迭代器反转时,反转的版本并不指向范围内的相同元素,而是指向它前面的元素。这样做是为了安排范围的过尾元素:指向范围中过尾元素的迭代器,在反转时,将被更改为指向范围的最后一个元素(而不是超过它)(如果反转,这将是范围的第一个元素)。如果指向范围内第一个元素的迭代器被反转,则反转后的迭代器指向第一个元素之前的元素(如果反转,这将是范围的后端元素)。

可以使用内部while循环:

while (true)
{
    // do your comparison here
    if (itR == sSet.begin())
        break;
    --itR;
}