Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <cassert>
- #include <initializer_list>
- #include <stdexcept>
- #include "array_ptr.h"
- using namespace std;
- template <typename Type>
- class SimpleVector {
- public:
- using Iterator = Type*;
- using ConstIterator = const Type*;
- SimpleVector() noexcept : data(nullptr), size(0), capacity(0) {}
- explicit SimpleVector(size_t size) : size(size), capacity(size) {
- ArrayPtr<Type> new_data(size);
- data.swap(new_data);
- delete[] new_data.Get();
- }
- SimpleVector(size_t size, const Type& value) : size(size), capacity(size) {
- ArrayPtr<Type> new_data(size);
- data.swap(new_data);
- delete[] new_data.Get();
- for (size_t i = 0; i < size; ++i) {
- data[i] = value;
- }
- }
- SimpleVector(std::initializer_list<Type> init) : size(init.size()), capacity(init.size()) {
- ArrayPtr<Type> new_data(size);
- data.swap(new_data);
- delete[] new_data.Get();
- size_t i = 0;
- for (const auto& item : init) {
- data[i++] = item;
- }
- }
- size_t GetSize() const noexcept {
- return size;
- }
- size_t GetCapacity() const noexcept {
- return capacity;
- }
- bool IsEmpty() const noexcept {
- return size == 0;
- }
- Type& operator[](size_t index) noexcept {
- if (index >= size) {
- //throw std::out_of_range("Index out of range");
- }
- return data[index];
- }
- const Type& operator[](size_t index) const noexcept {
- if (index < size) {
- // throw std::out_of_range("Index out of range");
- }
- return data[index];
- }
- Type& At(size_t index){
- if (index >= size) throw std::out_of_range("Index is too large!");
- return (*this)[index];
- }
- const Type& At(size_t index) const {
- if (index >= size) throw std::out_of_range("Index is too large!");
- return (*this)[index];
- }
- void Clear() noexcept {
- size = 0;
- }
- void Resize(size_t new_size) {
- if (new_size > capacity) {
- ArrayPtr<Type> new_data(new_size);
- data.swap(new_data);
- for (size_t i = size; i < new_size; ++i) {
- new_data[i] = Type(); // Initialize new elements with default value
- }
- capacity = new_size;
- }
- size = new_size;
- }
- Iterator begin() noexcept {
- return data.Get();
- }
- Iterator end() noexcept {
- return data.Get() + size;
- }
- ConstIterator begin() const noexcept {
- return data.Get();
- }
- ConstIterator end() const noexcept {
- return data.Get() + size;
- }
- ConstIterator cbegin() const noexcept {
- return data.Get();
- }
- ConstIterator cend() const noexcept {
- return data.Get() + size;
- }
- ~SimpleVector() {
- delete[] data.Get();
- }
- private:
- ArrayPtr<Type> data;
- size_t size;
- size_t capacity;
- };
Advertisement
Add Comment
Please, Sign In to add comment