What is the correct way of using C++11's range-based for?

后端 未结 4 898
面向向阳花
面向向阳花 2020-11-22 10:04

What is the correct way of using C++11\'s range-based for?

What syntax should be used? for (auto elem : container), or for (auto&

4条回答
  •  醉梦人生
    2020-11-22 10:56

    While the initial motivation of the range-for loop might have been ease of iterating over the elements of a container, the syntax is generic enough to be useful even for objects that are not purely containers.

    The syntactic requirement for the for-loop is that range_expression support begin() and end() as either functions -- either as member functions of the type that it evaluates to or as non-member functions what take an instance of the type.

    As a contrived example, one can generate a range of numbers and iterate over the range using the following class.

    struct Range
    {
       struct Iterator
       {
          Iterator(int v, int s) : val(v), step(s) {}
    
          int operator*() const
          {
             return val;
          }
    
          Iterator& operator++()
          {
             val += step;
             return *this;
          }
    
          bool operator!=(Iterator const& rhs) const
          {
             return (this->val < rhs.val);
          }
    
          int val;
          int step;
       };
    
       Range(int l, int h, int s=1) : low(l), high(h), step(s) {}
    
       Iterator begin() const
       {
          return Iterator(low, step);
       }
    
       Iterator end() const
       {
          return Iterator(high, 1);
       }
    
       int low, high, step;
    }; 
    

    With the following main function,

    #include 
    
    int main()
    {
       Range r1(1, 10);
       for ( auto item : r1 )
       {
          std::cout << item << " ";
       }
       std::cout << std::endl;
    
       Range r2(1, 20, 2);
       for ( auto item : r2 )
       {
          std::cout << item << " ";
       }
       std::cout << std::endl;
    
       Range r3(1, 20, 3);
       for ( auto item : r3 )
       {
          std::cout << item << " ";
       }
       std::cout << std::endl;
    }
    

    one would get the following output.

    1 2 3 4 5 6 7 8 9 
    1 3 5 7 9 11 13 15 17 19 
    1 4 7 10 13 16 19 
    

提交回复
热议问题