diff --git a/src/lol/base/array.h b/src/lol/base/array.h index 06594ae4..97ec5a7a 100644 --- a/src/lol/base/array.h +++ b/src/lol/base/array.h @@ -193,12 +193,13 @@ public: { T tmp = x; Reserve(m_count * 13 / 8 + 8); - new (&m_data[m_count++]) Element(tmp); + new (&m_data[m_count]) Element(tmp); } else { - new (&m_data[m_count++]) Element(x); + new (&m_data[m_count]) Element(x); } + ++m_count; return *this; } @@ -246,14 +247,19 @@ public: inline void Insert(T const &x, int pos) { - ArrayBase tmp; - for (int i = 0; i < m_count; i++) + ASSERT(pos >= 0); + ASSERT(pos <= m_count); + + if (m_count >= m_reserved) + Reserve(m_count * 13 / 8 + 8); + + for (int i = m_count; i > pos; --i) { - if (i == pos) - tmp.Push(x); - tmp.Push(m_data[i]); + new (&m_data[i]) Element(m_data[i - 1]); + m_data[i - 1].~Element(); } - *this = tmp; + new (&m_data[pos]) Element(x); + ++m_count; } inline int Find(T const &x) diff --git a/test/unit/array.cpp b/test/unit/array.cpp index 91067f89..31c644a1 100644 --- a/test/unit/array.cpp +++ b/test/unit/array.cpp @@ -147,6 +147,30 @@ LOLUNIT_FIXTURE(ArrayTest) LOLUNIT_ASSERT_EQUAL(20, a[1].m2); } + LOLUNIT_TEST(ArrayInsert) + { + Array a; + a << 1 << 2; + + a.Insert(5, 0); + LOLUNIT_ASSERT_EQUAL(5, a[0]); + LOLUNIT_ASSERT_EQUAL(1, a[1]); + LOLUNIT_ASSERT_EQUAL(2, a[2]); + + a.Insert(6, 3); + LOLUNIT_ASSERT_EQUAL(5, a[0]); + LOLUNIT_ASSERT_EQUAL(1, a[1]); + LOLUNIT_ASSERT_EQUAL(2, a[2]); + LOLUNIT_ASSERT_EQUAL(6, a[3]); + + a.Insert(7, 2); + LOLUNIT_ASSERT_EQUAL(5, a[0]); + LOLUNIT_ASSERT_EQUAL(1, a[1]); + LOLUNIT_ASSERT_EQUAL(7, a[2]); + LOLUNIT_ASSERT_EQUAL(2, a[3]); + LOLUNIT_ASSERT_EQUAL(6, a[4]); + } + LOLUNIT_TEST(ArrayConcat) { Array a, b;