vector_axx.hpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (C) 2008-2018 Lorenzo Caminiti
  2. // Distributed under the Boost Software License, Version 1.0 (see accompanying
  3. // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
  4. // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html
  5. //[cline90_vector_axx
  6. // Extra spaces, newlines, etc. for visual alignment with this library code.
  7. template<typename T>
  8. class vector {
  9. legal: // Class invariants (legal).
  10. size() >= 0;
  11. public:
  12. explicit vector(int count = 10) :
  13. data_(new T[count]),
  14. size_(count)
  15. {
  16. for(int i = 0; i < size_; ++i) data_[i] = T();
  17. }
  18. virtual ~vector() { delete[] data_; }
  19. int size() const { return size_; }
  20. void resize(int count) {
  21. T* slice = new T[count];
  22. for(int i = 0; i < count && i < size_; ++i) slice[i] = data_[i];
  23. delete[] data_;
  24. data_ = slice;
  25. size_ = count;
  26. }
  27. T& operator[](int index) { return data_[index]; }
  28. T& operator[](int index) const { return data_[index]; }
  29. axioms: // Preconditions (require) and postconditions (promise) for each func.
  30. [int count; require count >= 0; promise size() == count] vector(count);
  31. [int count; require count >= 0; promise size() == count] resize(count);
  32. [int index; require index >= 0 && index < size()] (*this)[x]; // Op[].
  33. [int index; require index >= 0 && index < size()] (*this)[x] const; // Op[].
  34. private:
  35. T* data_;
  36. int size_;
  37. };
  38. // End.
  39. //]