-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVectorLife.cpp
More file actions
105 lines (88 loc) · 2.44 KB
/
VectorLife.cpp
File metadata and controls
105 lines (88 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<string.h>
#include"VectorLife.h"
using namespace std;
//static member initialization
const size_t VectorLife :: INITAL_CAPACITY = 12;
/**
* Use of Initialization list : Improve the performance @ Compiler level
* http://www.parashift.com/c++-faq-lite/init-lists.html
*/
VectorLife :: VectorLife(size_t n):
num_items(n),
capacity(max(n,INITAL_CAPACITY)),
item_ptr (new string[capacity])
{
}
VectorLife::VectorLife(const VectorLife &other_vec):
num_items(other_vec.num_items),
capacity(other_vec.capacity),
item_ptr(new string[other_vec.num_items])
{
for(size_t i=0;i<num_items;i++) {
item_ptr[i] = other_vec.item_ptr[i];
}
}
//VectorLife :: VectorLife(size_t n) {
// num_items = n;
// capacity = max(n, INITAL_CAPACITY);
// item_ptr = new string[capacity];
//}
VectorLife:: ~VectorLife() {
delete [] item_ptr;
}
VectorLife& VectorLife::operator=(const VectorLife& other_vec) {
VectorLife(other_vec); //Use deep copy constructor
return (*this);
//http://stackoverflow.com/questions/2750316/this-vs-this-in-c
/**
* If you had a function that returned this,
* it would be a pointer to the current object,
* while a function that returned *this would be a "clone" of the
* current object, allocated on the stack --
* unless you have specified the return type of the method to return
* a reference.
*/
}
std::string& VectorLife::operator[](size_t index) {
if(index < num_items) {
// return this->item_ptr[index];
return item_ptr[index];
} else {
throw std::runtime_error("index out of range");
}
}
const std::string& VectorLife::operator[](size_t index) const{
if(index < num_items) {
// return this->item_ptr[index];
return item_ptr[index];
} else {
throw std::runtime_error("index out of range");
}
}
string& VectorLife::front() {
return (*this)[0];
}
const string& VectorLife::front() const{
return (*this) [0];
}
string& VectorLife::back() {
return (*this)[num_items -1];
}
const string& VectorLife::back() const{
return (*this) [num_items -1];
}
size_t VectorLife::get_size() const {
return capacity;
}
int main() {
VectorLife ubv(3); ubv[0] = "this"; ubv[1] = "is"; ubv[2] = "good!";
cout << ubv[0] << " " << ubv[1] << " " << ubv[2] << endl;
ubv.front() = "THIS";
ubv.back() = "GOOD!";
cout << ubv.front() << " " << ubv[1] << " " << ubv[2] << endl;
try {
cout << ubv[4] << endl;
} catch (exception &e) {
cout << e.what() << endl;
}
}