I'm learning C++, so I decided to make a simpler clone of std::vector
.
Concerns:
- I have seen people defining methods outside of the class, and only prototyping them inside the class. Should I be doing this too?
- I'm new to lower-level languages that require memory management, so there might be leaks.
- Are there any performance optimizations I could make?
- Is my general style good?
My code:
#include <iostream>
#include <algorithm>
template <class element>
class Vector {
private:
int len, cap;
element* arr;
void allocate_to_len() {
int new_cap = min(cap, 1); // size-0 vectors wont loop infinitely
while (len > new_cap) {
new_cap *= 2;
}
resize(new_cap);
}
public:
Vector() : Vector(10) {}
Vector(int size) {
len = 0;
cap = size;
arr = new element[size];
}
Vector(const Vector<element>& v) {
len = v.length();
cap = v.capac();
arr = new element[cap];
for (int i = 0; i < len; i++) {
arr[i] = v.get_value(i);
}
}
~Vector() {
delete[] arr;
}
element& operator[](int index) {
if (index < 0 || index >= len) {
throw "Index out of range";
}
return arr[index];
}
int length() const {
return len;
}
int capac() const {
return cap;
}
element get_value(int index) const {
if (index < 0 || index >= len) {
throw "Index out of range";
}
return arr[index];
}
void resize(int size) {
cap = size;
element* newarr = new element[size];
len = std::min(len, cap);
for (int i=0; i < len; i++) {
newarr[i] = arr[i];
}
arr = newarr;
}
void append(element item) {
len += 1;
allocate_to_len();
arr[len - 1] = item;
}
void extend(Vector<element> d) {
int length = d.length();
int old_len = len;
len += length;
allocate_to_len();
for (int i=0; i < length; i++) {
arr[i + old_len] = d[i];
}
}
};
int main() {
// Tests:
Vector<int> d;
d.append(1);
d.append(2);
d.append(3);
for (int i=0; i<d.length(); i++) {
std::cout << d[i] << "\n";
}
std::cout << "\n";
Vector<int> d2;
d2.append(4);
d2.append(5);
d2.append(6);
d.extend(d2);
for (int i = 0; i < d.length(); i++) {
std::cout << d[i] << "\n";
}
std::cout << "\n";
d.resize(4);
for (int i = 0; i < d.length(); i++) {
std::cout << d[i] << "\n";
}
}