Цитата(gosn1ck @ 15.6.2009, 19:14 ) | можно в студию ваш варинт решения задачи? был бы благодарен очень |
по минимуму я бы его так реализовал: только основные операции: 1) перераспределение вектора в другую область памяти при исчерпании резервной памяти - функция reallocate 2) вставка элемента в вектор 3) итераторы для работы с алгоритмами 4) размер вектора - функция size
Код | #include <vector> #include <algorithm> #include <iostream> #include <iterator>
template <class T> class Vector { public: typedef T* iterator; iterator beg_it; iterator end_it;
Vector() : elements(0), first_free(0), end(0), beg_it(elements), end_it(first_free) { } T &operator[](size_t pos) { return elements[pos]; } const T &operator[](size_t pos) const { return elements[pos]; } void push_back(const T&); size_t size() const; private: static std::allocator<T> alloc; void reallocate(); T* elements; T* first_free; T* end; };
template <class T> std::allocator<T> Vector<T>::alloc;
template <class T> size_t Vector<T>::size() const { return first_free - elements; }
template <class T> void Vector<T>::push_back(const T& t) { if (first_free == end) reallocate(); alloc.construct(first_free, t); end_it = ++first_free; }
template <class T> void Vector<T>::reallocate() { ptrdiff_t size = first_free - elements; ptrdiff_t newcapacity = 2 * std::max(size, 1);
T* newelements = alloc.allocate(newcapacity); std::uninitialized_copy(elements, first_free, newelements);
for (T *p = first_free; p != elements; /* empty */) alloc.destroy(--p);
if (elements) alloc.deallocate(elements, end - elements);
elements = newelements; first_free = elements + size; end = elements + newcapacity;
beg_it = elements; end_it = first_free; }
int main() { Vector<int> v; v.push_back(30); v.push_back(20); v.push_back(60); v.push_back(40); v.push_back(10); size_t sz = v.size();
std::sort(v.beg_it, v.end_it); std::copy(v.beg_it, v.end_it, std::ostream_iterator<int>(std::cout, "\n"));
return 0; }
|
|