MyVector
myvector.cpp
Go to the documentation of this file.
1 #include "myvector.h"
2 #include <cassert> // NEW: assert()
3 #include <iostream>
4 #include <new> // NEW: new(nothrow)
5 
6 using namespace std;
7 
8 MyVector :: MyVector(const long long int n ) // Standard-, Parameterkonstruktor
9  : length_( n>0 ? n : 0), val_(nullptr)
10 {
11  //
12  // Restrict available memory in the shell by:
13  // ulimit
14  //
15  cout << "--> " << length_ << endl;
16  if ( length_>0 )
17  {
18 // val_ = new(nothrow) double [length_]; // no exception is thrown
19  val_ = new double [length_]; // throws "bad_alloc" in case of insufficient memory
20 // assert(val_ != nullptr);
21  cout << "## " << val_ << endl;
22  }
23 }
24 
25 // ToDo: Add copy constructor
26 // use constructor delegation
27 #ifndef WRONG_CODE
29  : MyVector(orig.length_)
30  {
31  for (long long int i=0; i<length_; i++)
32  {
33  val_[i] = orig.val_[i];
34  }
35  }
36 #endif
37 
38 MyVector :: ~MyVector() // Destruktor
39 {
40  delete [] val_;
41 }
42 
43 // ToDo: Add assignment operator
44 #ifndef WRONG_CODE
45 MyVector& MyVector :: operator=(MyVector const &orig) // copy assignment
46 {
47  if (this != &orig)
48  {
49  delete [] val_;
50  length_ = orig.length_;
51  if (length_>0)
52  {
53  val_ = new double [length_];
54  for (long long int i=0; i<length_; i++)
55  {
56  val_[i] = orig.val_[i];
57  }
58  }
59  else
60  {
61  val_ = nullptr;
62  }
63  }
64  return *this;
65 }
66 #endif
67 
68 ostream & operator<<(ostream & s, MyVector const &orig)
69 {
70  long long int i;
71 
72  s << endl << "MyVector has " << orig.size() << " components" << endl;
73  for (i=0; i<orig.size(); i++)
74  {
75  s << orig[i]<< " ";
76  }
77  s << endl;
78 
79  return s;
80 }
81 
My own vector class.
Definition: myvector.h:11
MyVector(const long long int n=0)
Allocates a vector with n elements on the heap.
Definition: myvector.cpp:8
const long long int & size() const
Returns the number of elements.
Definition: myvector.h:53
long long int length_
number of elements
Definition: myvector.h:102
virtual ~MyVector()
Deallocates the heap memory.
Definition: myvector.cpp:38
MyVector & operator=(MyVector const &orig)
Reallocates the vector with the same elements as vector orig and copies its elements.
Definition: myvector.cpp:45
double * val_
pointer to allocated memory
Definition: myvector.h:103
ostream & operator<<(ostream &s, MyVector const &orig)
Definition: myvector.cpp:68