Constuctor chaining, better/more efficient moving
This commit is contained in:
parent
5c20408a04
commit
1a0b3697f2
2 changed files with 22 additions and 11 deletions
|
@ -2,14 +2,16 @@
|
|||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
|
||||
Vec::Vec() : cap(INITIAL_LEN), w_idx(0), arr(nullptr) {
|
||||
std::cout << "Allocating vector" << std::endl;
|
||||
arr = new T[INITIAL_LEN];
|
||||
Vec::Vec() : Vec(INITIAL_LEN) {}
|
||||
|
||||
Vec::Vec(std::size_t size) : cap(size), w_idx(0), arr(new T[size]) {
|
||||
std::cout << "Allocating vector of size " << size << std::endl;
|
||||
}
|
||||
|
||||
Vec::Vec(std::initializer_list<T> il) : Vec() {
|
||||
for (auto &a : il) push_back(a);
|
||||
Vec::Vec(std::initializer_list<T> il) : Vec(il.size()) {
|
||||
for (auto &elem : il) push_back(std::move(elem));
|
||||
}
|
||||
|
||||
Vec::~Vec() {
|
||||
|
@ -26,12 +28,18 @@ T &Vec::operator[](std::size_t idx) const noexcept {
|
|||
exit(1);
|
||||
}
|
||||
|
||||
void Vec::push_back(const T &value) noexcept {
|
||||
void Vec::push_back(const T &value) {
|
||||
arr[w_idx++] = value;
|
||||
|
||||
if (w_idx == cap) {
|
||||
if (w_idx == cap)
|
||||
resize(cap * 2);
|
||||
}
|
||||
|
||||
void Vec::push_back(T &&value) {
|
||||
arr[w_idx++] = std::move(value);
|
||||
|
||||
if (w_idx == cap)
|
||||
resize(cap * 2);
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t Vec::size() const { return w_idx; }
|
||||
|
@ -39,9 +47,10 @@ std::size_t Vec::size() const { return w_idx; }
|
|||
std::size_t Vec::capacity() const noexcept { return cap; }
|
||||
|
||||
void Vec::resize(std::size_t newsize) {
|
||||
std::cout << "Reallocating" << std::endl;
|
||||
std::cout << "Reallocating: " << cap << " to " << newsize << std::endl;
|
||||
|
||||
T *newarr = new T[newsize];
|
||||
std::memcpy(newarr, arr, w_idx);
|
||||
std::move(arr, arr + w_idx, newarr);
|
||||
delete[] arr;
|
||||
arr = newarr;
|
||||
cap = newsize;
|
||||
|
|
|
@ -13,6 +13,7 @@ class Vec {
|
|||
|
||||
public:
|
||||
Vec();
|
||||
explicit Vec(std::size_t);
|
||||
Vec(std::initializer_list<T>);
|
||||
Vec(const Vec &other); // Copy
|
||||
Vec(Vec &&other) noexcept; // Move
|
||||
|
@ -25,7 +26,8 @@ class Vec {
|
|||
std::size_t size() const;
|
||||
std::size_t capacity() const noexcept;
|
||||
|
||||
void push_back(const T &value) noexcept;
|
||||
void push_back(const T &value); // May except
|
||||
void push_back(T &&value);
|
||||
void pop_back() noexcept;
|
||||
void clear() noexcept;
|
||||
|
||||
|
|
Loading…
Reference in a new issue