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

后端 未结 9 2253
长情又很酷
长情又很酷 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条回答
  •  时光取名叫无心
    2020-11-22 08:22

    Here, I am sharing the simplest example of creating custom type, that will work with "range-based for loop":

    #include
    using namespace std;
    
    template
    class MyCustomType
    {
    private:
        T *data;
        int indx;
    public:
        MyCustomType(){
            data = new T[sizeOfArray];
            indx = -1;
        }
        ~MyCustomType(){
            delete []data;
        }
        void addData(T newVal){
            data[++indx] = newVal;
        }
    
        //write definition for begin() and end()
        //these two method will be used for "ranged based loop idiom"
        T* begin(){
            return &data[0];
        }
        T* end(){
            return  &data[sizeOfArray];
        }
    };
    int main()
    {
        MyCustomType numberList;
        numberList.addData(20.25);
        numberList.addData(50.12);
        for(auto val: numberList){
            cout<

    Hope, it will be helpful for some novice developer like me :p :)
    Thank You.

提交回复
热议问题