Why can I not convert a reverse iterator to a forward iterator?

前端 未结 3 1503
情话喂你
情话喂你 2021-02-13 22:36

Well, I know why, it\'s because there isn\'t a conversion, but why isn\'t there a conversion? Why can forward iterators be turned to reverse iterators but not the other way roun

3条回答
  •  别那么骄傲
    2021-02-13 23:04

    It's very common to have two (reverse) iterators span a range of values (such as in begin(),end() and rbegin(),rend()). For any range described by the two reverse iterators rA,rB, the range rB.base(),rA.base() will span the same range in the forward direction.

    #include 
    #include 
    #include 
    
    int main() {
      std::vector vec{10,11,12,13,14,15};
    
      // spans the range from 13 to 10
      auto rfirst=std::rbegin(vec)+2;
      auto rlast=std::rend(vec);
    
      // Loops forward, prints 10 11 12 13
      for(auto it = rlast.base(); it != rfirst.base(); ++it){
        std::cout << *it << " ";
      }
    }
    

    If conceptually you are only interested in a single item (such as the result of find_if), then use make_forward by @visitor. Even in this case, the range idea helps to keep track of the validity of the reverse iterator:

    #include 
    #include 
    #include 
    #include 
    
    int main() {
      std::vector vec{10,11,12,13,14,15};
    
      auto rfirst=std::rbegin(vec);
      auto rlast=std::rend(vec);
    
      auto rfound = std::find_if(rfirst,rlast, [](int v){ return v<13; });
    
      if(rfound != rlast){
        std::cout << *rfound << " "; // prints 12
        auto forwardFound = make_forward(rfound) ; 
        std::cout << *forwardFound << " "; // prints 12
      }
    }
    

提交回复
热议问题