Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstddef>
- #include <iostream>
- class Vector {
- private:
- int * buffer_;
- size_t size_;
- size_t capacity_;
- public:
- Vector() {
- size_ = 0;
- capacity_ = 0;
- buffer_ = nullptr;
- }
- Vector(const Vector& other) {
- buffer_ = other.buffer_;
- size_ = other.size_;
- capacity_ = other.capacity_;
- }
- void reserve(size_t size) {
- int * new_buf = new int[size];
- for (size_t i = 0; i < capacity_; ++i) {
- new_buf[i] = buffer_[i];
- }
- capacity_ = size;
- delete [] buffer_;
- buffer_ = new_buf;
- }
- void push_back(int val) {
- if (size_ >= capacity_) {
- size_t new_cap = capacity_ ? capacity_ * 2 : 1;
- reserve(new_cap);
- }
- buffer_[size_++] = val;
- }
- void pop_back() {
- if (!size_)
- return;
- --size_;
- }
- const int operator[](size_t i) const {
- return buffer_[i];
- }
- int &operator[](size_t i) {
- return buffer_[i];
- }
- Vector& operator=(const Vector& other) {
- delete [] buffer_;
- buffer_ = other.buffer_;
- size_ = other.size_;
- return *this;
- }
- size_t size() {
- return size_;
- }
- ~Vector() {
- delete [] buffer_;
- }
- };
- int main() {
- Vector a;
- a.push_back(4);
- a.push_back(6);
- a.push_back(7);
- a.push_back(8);
- a.push_back(9);
- std::cout << "size " << a.size() << std::endl;
- for (size_t i = 0; i < a.size(); ++i) {
- std::cout << a[i] << ' ';
- }
- std::cout << std::endl;
- Vector b = a;
- std::cout << "size of b " << b.size() << std::endl;
- for (size_t i = 0; i < b.size(); ++i) {
- std::cout << b[i] << ' ';
- }
- std::cout << std::endl;
- a.pop_back();
- std::cout << "size " << a.size() << std::endl;
- for (size_t i = 0; i < a.size(); ++i) {
- std::cout << a[i] << ' ';
- }
- std::cout << std::endl;
- a.pop_back();
- std::cout << "size " << a.size() << std::endl;
- for (size_t i = 0; i < a.size(); ++i) {
- std::cout << a[i] << ' ';
- }
- std::cout << std::endl;
- a.pop_back();
- std::cout << "size " << a.size() << std::endl;
- for (size_t i = 0; i < a.size(); ++i) {
- std::cout << a[i] << ' ';
- }
- std::cout << std::endl;
- a.pop_back();
- std::cout << "size " << a.size() << std::endl;
- for (size_t i = 0; i < a.size(); ++i) {
- std::cout << a[i] << ' ';
- }
- std::cout << std::endl;
- a.pop_back();
- std::cout << "size " << a.size() << std::endl;
- for (size_t i = 0; i < a.size(); ++i) {
- std::cout << a[i] << ' ';
- }
- std::cout << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment