Home > Mobile >  How to implement begin and end to a template class in c
How to implement begin and end to a template class in c

Time:12-17

I have a problem. I need to implement my own methods for begin and end to iterate with for-loop through array. But i'm not so sure how to do it. I write code as below

template <typename T> 
class container {
public:
    size_t n;
    T *p;
    container(std::initializer_list<T> L) {
        int i = 0;
        n = L.size();
        p = new T[n];
        for(auto element : L) {
            p[i] = element; 
            i  ;
        }
    }
    T getArray() {
      return *p;
    }
    T *begin(container<T> &cref);
    T *end(container<T> &cref);

    ~container() { delete[] p; }
    T &operator[](size_t k) { return p[k]; }
    void info() {
        std::cout << "Ilość elementów w tablicy: " << n << "\n";
        for(const char& c : p)     
            {         
                std::cout << c << std::endl;     
            }    
        std::cout << "Typ danych: " << typeid(*p).name() << '\n';
    };
    size_t length() const { return n; }
};


template <typename T>
T* container<T>::begin(container<T> &cref) {
    return cref.getArray()[0];
}

template <typename T>
T* container<T>::end(container<T> &cref) {
    return cref.getArray()[0   cref.length()];
}


int main(int argc, char** argv) {

    container<char> Z{'a', 'b', 'c', 'd'};
    Z.info();
    std::cout << Z.length();
    return 0;
}

Can someone tell me how to do it and use iterators with for-loop like this:

for(const char& c : p)     
    {         
        std::cout << c << std::endl;     
    }    

CodePudding user response:

T is the element type; p is a pointer to the first array element, and begin and end should not take an argument (you're going to iterate over *this).

You want

T* getArray() { return p; }

and

template <typename T>
T* container<T>::begin() {
    return p;
}

template <typename T>
T* container<T>::end() {
    return p   length();
}
  • Related