aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMITSUNARI Shigeo <herumi@nifty.com>2018-05-28 05:55:29 +0800
committerMITSUNARI Shigeo <herumi@nifty.com>2018-05-28 05:55:29 +0800
commite8f89a57f81ba4ad96f08040b4d48b9e1ccca3a0 (patch)
tree1595e8cdfae50311124f7be51612d7aa13c4e2cb
parentb3c2b12093c9f04970f4acfb0dd825af4e0638ba (diff)
downloaddexon-mcl-e8f89a57f81ba4ad96f08040b4d48b9e1ccca3a0.tar.gz
dexon-mcl-e8f89a57f81ba4ad96f08040b4d48b9e1ccca3a0.tar.zst
dexon-mcl-e8f89a57f81ba4ad96f08040b4d48b9e1ccca3a0.zip
add array.hpp
-rw-r--r--include/mcl/array.hpp84
1 files changed, 84 insertions, 0 deletions
diff --git a/include/mcl/array.hpp b/include/mcl/array.hpp
new file mode 100644
index 0000000..5c494c2
--- /dev/null
+++ b/include/mcl/array.hpp
@@ -0,0 +1,84 @@
+#pragma once
+/**
+ @file
+ @brief tiny vector class
+ @author MITSUNARI Shigeo(@herumi)
+ @license modified new BSD license
+ http://opensource.org/licenses/BSD-3-Clause
+*/
+#include <malloc.h>
+#include <stddef.h>
+
+namespace mcl {
+template<class T>
+class Array {
+ T *p_;
+ size_t n_;
+ Array(const Array&);
+ void operator=(const Array&);
+ template<class U>
+ void swap_(U& x, U& y) const
+ {
+ U t;
+ t = x;
+ x = y;
+ y = t;
+ }
+public:
+ Array() : p_(0), n_(0) {}
+ ~Array()
+ {
+ free(p_);
+ }
+ bool resize(size_t n)
+ {
+ if (n <= n_) {
+ n_ = n;
+ if (n == 0) {
+ free(p_);
+ p_ = 0;
+ }
+ return true;
+ }
+ T *q = (T*)malloc(sizeof(T) * n);
+ if (q == 0) return false;
+ for (size_t i = 0; i < n_; i++) {
+ q[i] = p_[i];
+ }
+ free(p_);
+ p_ = q;
+ n_ = n;
+ return true;
+ }
+ bool copy(const Array<T>& rhs)
+ {
+ if (this == &rhs) return true;
+ if (n_ < rhs.n_) {
+ clear();
+ if (!resize(rhs.n_)) return false;
+ }
+ for (size_t i = 0; i < rhs.n_; i++) {
+ p_[i] = rhs.p_[i];
+ }
+ n_ = rhs.n_;
+ return true;
+ }
+ void clear()
+ {
+ free(p_);
+ p_ = 0;
+ n_ = 0;
+ }
+ size_t size() const { return n_; }
+ void swap(Array<T>& rhs)
+ {
+ swap_(p_, rhs.p_);
+ swap_(n_, rhs.n_);
+ }
+ T& operator[](size_t n) { return p_[n]; }
+ const T& operator[](size_t n) const { return p_[n]; }
+ T* data() { return p_; }
+ const T* data() const { return p_; }
+};
+} // mcl
+