How to make the for each loop function in C++ work with a custom class

前端 未结 5 1234
遇见更好的自我
遇见更好的自我 2020-12-05 04:18

I\'m new to C/C++ programming, but I\'ve been programming in C# for 1.5 years now. I like C# and I like the List class, so I thought about making a List class in C++ as an e

5条回答
  •  情话喂你
    2020-12-05 04:36

    Firstly, the syntax of a for-each loop in C++ is different from C# (it's also called a range based for loop. It has the form:

    for(  : ) { ... }
    

    So for example, with an std::vector vec, it would be something like:

    for(int i : vec) { ... }
    

    Under the covers, this effectively uses the begin() and end() member functions, which return iterators. Hence, to allow your custom class to utilize a for-each loop, you need to provide a begin() and an end() function. These are generally overloaded, returning either an iterator or a const_iterator. Implementing iterators can be tricky, although with a vector-like class it's not too hard.

    template 
    struct List
    {
        T* store;
        std::size_t size;
        typedef T* iterator;
        typedef const T* const_iterator;
    
        ....
    
        iterator begin() { return &store[0]; }
        const_iterator begin() const { return &store[0]; }
        iterator end() { return &store[size]; }
        const_iterator end() const { return &store[size]; }
    
        ...
     };
    

    With these implemented, you can utilize a range based loop as above.

提交回复
热议问题