From 7060e656ad6e052fc19553723a1e39b9ed0b0f6c Mon Sep 17 00:00:00 2001 From: Charles Ellis Date: Fri, 1 Nov 2019 17:32:01 -0700 Subject: [PATCH] Chapter 3 vector and container class code --- ch03/container.hpp | 11 +++++++++++ ch03/use.cpp | 22 ++++++++++++++++++++++ ch03/vector.cpp | 9 +++++++++ ch03/vector.hpp | 28 ++++++++++++++++++++++++++++ ch03/vector_container.hpp | 20 ++++++++++++++++++++ 5 files changed, 90 insertions(+) create mode 100644 ch03/container.hpp create mode 100644 ch03/use.cpp create mode 100644 ch03/vector.cpp create mode 100644 ch03/vector.hpp create mode 100644 ch03/vector_container.hpp diff --git a/ch03/container.hpp b/ch03/container.hpp new file mode 100644 index 0000000..c2c0a93 --- /dev/null +++ b/ch03/container.hpp @@ -0,0 +1,11 @@ +#ifndef __CONTAINER_H__ +#define __CONTAINER_H__ + +class Container { +public: + virtual double& operator[](int) = 0; + virtual int size() const = 0; + virtual ~Container() {}; +}; + +#endif //__CONTAINER_H__ diff --git a/ch03/use.cpp b/ch03/use.cpp new file mode 100644 index 0000000..f8167e7 --- /dev/null +++ b/ch03/use.cpp @@ -0,0 +1,22 @@ +#include + +#include "container.hpp" +#include "vector_container.hpp" + +void use(Container& c) { + const int sz = c.size(); + + for(int i = 0; i != sz; ++i) { + std::cout << c[i] << '\n'; + } +} + +void g() { + Vector_container vc{10,9,8,7,6,5,4,3,2,1,0}; + + use(vc); +} + +int main() { + g(); +} diff --git a/ch03/vector.cpp b/ch03/vector.cpp new file mode 100644 index 0000000..fe8d9d7 --- /dev/null +++ b/ch03/vector.cpp @@ -0,0 +1,9 @@ +#include "vector.hpp" + +double& Vector::operator[](int i) { + return elem[i]; +} + +int Vector::size() const { + return sz; +} diff --git a/ch03/vector.hpp b/ch03/vector.hpp new file mode 100644 index 0000000..5527f83 --- /dev/null +++ b/ch03/vector.hpp @@ -0,0 +1,28 @@ +#ifndef __VECTOR_H__ +#define __VECTOR_H__ + +#include +#include + +class Vector { +private: + double* elem; + int sz; + +public: + Vector(int s) : elem{new double[s]}, sz{s} { + for(int i = 0; i != s; ++i) elem[i] = 0; + } + + Vector(std::initializer_list lst) + : elem{new double[lst.size()]}, sz{static_cast(lst.size())} { + std::copy(lst.begin(), lst.end(), elem); + } + + ~Vector() { delete[] elem; } + + double& operator[](int i); + int size() const; +}; + +#endif //__VECTOR_H__ diff --git a/ch03/vector_container.hpp b/ch03/vector_container.hpp new file mode 100644 index 0000000..1cf1527 --- /dev/null +++ b/ch03/vector_container.hpp @@ -0,0 +1,20 @@ +#ifndef __VECTOR_CONTAINER_H__ +#define __VECTOR_CONTAINER_H__ + +#include + +#include "container.hpp" +#include "vector.hpp" + +class Vector_container : public Container { + Vector v; +public: + Vector_container(int s) : v(s) {} + Vector_container(std::initializer_list lst) : v(lst) {} + ~Vector_container() {} + + double& operator[](int i) { return v[i]; } + int size() const { return v.size(); } +}; + +#endif //__VECTOR_CONTAINER_H__