Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <exception>
- #include <iostream>
- #include <stdexcept>
- class Vector {
- public:
- Vector();
- ~Vector();
- double at(unsigned int index) const;
- double operator[](unsigned int index) const { return at(index); }
- unsigned int size() const { return size_; }
- bool empty() const { return size_ == 0u;}
- void push_back(double value);
- private:
- static const unsigned int kInitialSize = 2;
- double* buffer_;
- unsigned int size_; // Количество хранимых элементов
- unsigned int capacity_; // Размер буфера
- void increase_buffer();
- };
- Vector::Vector() :
- buffer_(nullptr),
- size_(0),
- capacity_(0) {
- }
- Vector::~Vector() {
- delete[] buffer_;
- }
- double Vector::at(unsigned int index) const {
- if (index >= size_) throw std::out_of_range("No such index");
- return buffer_[index];
- }
- void Vector::push_back(double value) {
- if (size_ == capacity_) {
- increase_buffer();
- }
- buffer_[size_++] = value;
- }
- void Vector::increase_buffer() {
- unsigned int new_capacity = capacity_ == 0 ? kInitialSize : 2 * capacity_;
- double* new_buffer = new double[new_capacity];
- for (unsigned int i = 0; i < size_; ++i) {
- new_buffer[i] = buffer_[i];
- }
- delete[] buffer_;
- buffer_ = new_buffer;
- capacity_ = new_capacity;
- }
- void do_stuff() {
- Vector v;
- v.push_back(4.0);
- v.push_back(5.0);
- v.push_back(3.0);
- v.push_back(2.0);
- v.push_back(1.0);
- for (unsigned int i = 0; i <= v.size(); ++i) {
- std::cout << v[i] << " ";
- }
- }
- int main() {
- try {
- do_stuff();
- } catch (const std::exception& e) {
- std::cout << "ERROR! " << e.what();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement