Skip to content

Commit

Permalink
Chapter 3 vector and container class code
Browse files Browse the repository at this point in the history
  • Loading branch information
Hamled committed Nov 2, 2019
1 parent 81aea5b commit 7060e65
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 0 deletions.
11 changes: 11 additions & 0 deletions 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__
22 changes: 22 additions & 0 deletions ch03/use.cpp
@@ -0,0 +1,22 @@
#include <iostream>

#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();
}
9 changes: 9 additions & 0 deletions ch03/vector.cpp
@@ -0,0 +1,9 @@
#include "vector.hpp"

double& Vector::operator[](int i) {
return elem[i];
}

int Vector::size() const {
return sz;
}
28 changes: 28 additions & 0 deletions ch03/vector.hpp
@@ -0,0 +1,28 @@
#ifndef __VECTOR_H__
#define __VECTOR_H__

#include <initializer_list>
#include <algorithm>

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<double> lst)
: elem{new double[lst.size()]}, sz{static_cast<int>(lst.size())} {
std::copy(lst.begin(), lst.end(), elem);
}

~Vector() { delete[] elem; }

double& operator[](int i);
int size() const;
};

#endif //__VECTOR_H__
20 changes: 20 additions & 0 deletions ch03/vector_container.hpp
@@ -0,0 +1,20 @@
#ifndef __VECTOR_CONTAINER_H__
#define __VECTOR_CONTAINER_H__

#include <initializer_list>

#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<double> lst) : v(lst) {}
~Vector_container() {}

double& operator[](int i) { return v[i]; }
int size() const { return v.size(); }
};

#endif //__VECTOR_CONTAINER_H__

0 comments on commit 7060e65

Please sign in to comment.