// This file is one of a series that illustrates CheapVector (cv), // It’s an example of an STL-like container, including // an iterator. It’s not efficient, but that’s not the point. // // This version simply uses a native pointer as an iterator. // For example, if we’re storing doubles, the iterator is a double *. #ifndef CV_H_INCLUDED #define CV_H_INCLUDED #include // copy() // The Cheap Vector // It’s missing many things: // • copy ctor // • assignment // • assignment from initializer_list // • cbegin()/cend()/rbegin()/rend()/… // • empty() // • clear() // • value_type template class cv { public: typedef size_t size_type; typedef T *iterator; cv() = default; template cv(const std::initializer_list &il) : count(il.size()), data(new T[count]) { std::copy_n(il.begin(), count, data); } ~cv() { delete[] data; } size_type size() const { return count; } iterator begin() { return data; } iterator end() { return data+count; } T& operator[](size_type n) { return data[n]; } void push_back(const T &datum) { T *new_data = new T[count+1]; std::copy(data, data+count, new_data); delete[] data; data = new_data; data[count++] = datum; } private: size_type count = 0; T *data = nullptr; }; #endif /* CV_H_INCLUDED */