some vector work
parent
323e992ea5
commit
6c6e7b69f7
|
@ -1,6 +1,6 @@
|
|||
/* Default new/delete operator overloads for OctaSTD.
|
||||
*
|
||||
* This file is part of OctaSTD. See COPYING.txt for futher information.
|
||||
* This file is part of OctaSTD. See COPYING.md for futher information.
|
||||
*/
|
||||
|
||||
#ifndef OCTA_NEW_H
|
||||
|
|
|
@ -0,0 +1,12 @@
|
|||
/* Type traits for OctaSTD.
|
||||
*
|
||||
* This file is part of OctaSTD. See COPYING.md for futher information.
|
||||
*/
|
||||
|
||||
#ifndef OCTA_TYPE_TRAITS_H
|
||||
#define OCTA_TYPE_TRAITS_H
|
||||
|
||||
namespace octa {
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,16 +1,17 @@
|
|||
/* Self-expanding dynamic array implementation for OctaSTD.
|
||||
*
|
||||
* This file is part of OctaSTD. See COPYING.txt for futher information.
|
||||
* This file is part of OctaSTD. See COPYING.md for futher information.
|
||||
*/
|
||||
|
||||
#ifndef OCTA_VECTOR_H
|
||||
#define OCTA_VECTOR_H
|
||||
|
||||
#include <octa/new.h>
|
||||
#include <octa/type_traits.h>
|
||||
|
||||
namespace octa {
|
||||
template<typename T>
|
||||
class vector {
|
||||
class Vector {
|
||||
T *buf;
|
||||
size_t length, capacity;
|
||||
|
||||
|
@ -22,11 +23,49 @@ namespace octa {
|
|||
}
|
||||
|
||||
~vector() {
|
||||
resize(0);
|
||||
if (buf) delete[] (unsigned char *)buf;
|
||||
}
|
||||
|
||||
vector<T> &operator=(const vector<T> &v) {
|
||||
resize(0);
|
||||
if (v.length() > capacity) resize(v.length());
|
||||
for (size_t i = 0; i < v.length(); ++i) push(v[i]);
|
||||
return *this;
|
||||
}
|
||||
|
||||
T &push(const T &v) {
|
||||
if (length == capacity) resize(length + 1);
|
||||
new (&buf[length]) T(v);
|
||||
return buf[length++];
|
||||
}
|
||||
|
||||
T &push() {
|
||||
if (length == capacity) resize(length + 1);
|
||||
new (&buf[length]) T;
|
||||
return buf[length++];
|
||||
}
|
||||
|
||||
void resize(size_t n) {
|
||||
if (n <= length) {
|
||||
if (n == length) return;
|
||||
while (length > n) pop();
|
||||
return;
|
||||
}
|
||||
int old = capacity;
|
||||
if (!old)
|
||||
capacity = max(n, 8);
|
||||
else
|
||||
while (capacity < n) capacity += (capacity / 2);
|
||||
if (capacity <= old)
|
||||
return;
|
||||
unsigned char *nbuf = new unsigned char[capacity * sizeof(T)];
|
||||
if (old > 0) {
|
||||
if (length > 0) memcpy(nbuf, (void *)buf, length * sizeof(T));
|
||||
delete[] (unsigned char *)buf;
|
||||
}
|
||||
buf = (T *)buf;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue