How to make my custom type to work with “range-based for loops”?

后端 未结 9 2325
长情又很酷
长情又很酷 2020-11-22 08:06

Like many people these days I have been trying the different features that C++11 brings. One of my favorites is the \"range-based for loops\".

I understand that:

9条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 08:44

    I write my answer because some people might be more happy with simple real life example without STL includes.

    I have my own plain only data array implementation for some reason, and I wanted to use the range based for loop. Here is my solution:

     template 
     class PodArray {
     public:
       class iterator {
       public:
         iterator(DataType * ptr): ptr(ptr){}
         iterator operator++() { ++ptr; return *this; }
         bool operator!=(const iterator & other) const { return ptr != other.ptr; }
         const DataType& operator*() const { return *ptr; }
       private:
         DataType* ptr;
       };
     private:
       unsigned len;
       DataType *val;
     public:
       iterator begin() const { return iterator(val); }
       iterator end() const { return iterator(val + len); }
    
       // rest of the container definition not related to the question ...
     };
    

    Then the usage example:

    PodArray array;
    // fill up array in some way
    for(auto& c : array)
      printf("char: %c\n", c);
    

提交回复
热议问题