add FixedArray

dev
MITSUNARI Shigeo 7 years ago
parent 6815f44866
commit f02e5b8353
  1. 44
      include/mcl/array.hpp
  2. 28
      test/array_test.cpp

@ -10,6 +10,7 @@
#include <stddef.h>
namespace mcl {
template<class T>
class Array {
T *p_;
@ -80,5 +81,48 @@ public:
T* data() { return p_; }
const T* data() const { return p_; }
};
template<class T, size_t maxSize>
class FixedArray {
T p_[maxSize];
size_t n_;
FixedArray(const FixedArray&);
void operator=(const FixedArray&);
template<class U>
void swap_(U& x, U& y) const
{
U t;
t = x;
x = y;
y = t;
}
public:
FixedArray() : n_(0) {}
bool resize(size_t n)
{
if (n > maxSize) return false;
n_ = n;
return true;
}
bool copy(const FixedArray<T, maxSize>& rhs)
{
if (this == &rhs) return true;
for (size_t i = 0; i < rhs.n_; i++) {
p_[i] = rhs.p_[i];
}
n_ = rhs.n_;
return true;
}
void clear()
{
n_ = 0;
}
size_t size() const { return 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

@ -30,3 +30,31 @@ CYBOZU_TEST_AUTO(resize)
CYBOZU_TEST_EQUAL(b.size(), large);
CYBOZU_TEST_EQUAL_ARRAY(a.data(), b.data(), small);
}
CYBOZU_TEST_AUTO(FixedArray)
{
const size_t n = 5;
mcl::FixedArray<int, n> a, b;
CYBOZU_TEST_EQUAL(a.size(), 0);
CYBOZU_TEST_EQUAL(b.size(), 0);
bool ok = a.resize(n);
CYBOZU_TEST_ASSERT(ok);
CYBOZU_TEST_EQUAL(n, a.size());
for (size_t i = 0; i < n; i++) {
a[i] = i;
}
ok = b.copy(a);
CYBOZU_TEST_ASSERT(ok);
CYBOZU_TEST_EQUAL(b.size(), n);
CYBOZU_TEST_EQUAL_ARRAY(a.data(), b.data(), n);
const size_t small = n - 1;
ok = b.resize(small);
CYBOZU_TEST_ASSERT(ok);
CYBOZU_TEST_EQUAL(b.size(), small);
CYBOZU_TEST_EQUAL_ARRAY(a.data(), b.data(), small);
const size_t large = n + 1;
ok = b.resize(large);
CYBOZU_TEST_ASSERT(!ok);
}

Loading…
Cancel
Save