Browse Source

base: Array::Remove(int) now accepts a negative index to remove elements

from the end. Also added Array::RemoveSwap() for faster removes at the
expense of element ordering.
legacy
Sam Hocevar sam 11 years ago
parent
commit
ef0bd031ab
2 changed files with 51 additions and 1 deletions
  1. +21
    -1
      src/lol/base/array.h
  2. +30
    -0
      test/unit/array.cpp

+ 21
- 1
src/lol/base/array.h View File

@@ -187,9 +187,12 @@ public:


void Remove(int pos, int todelete = 1) void Remove(int pos, int todelete = 1)
{ {
ASSERT(pos >= 0);
ASSERT(todelete >= 0); ASSERT(todelete >= 0);
ASSERT(pos - todelete >= -m_count - 1);
ASSERT(pos + todelete <= m_count); ASSERT(pos + todelete <= m_count);
if (pos < 0)
pos = m_count + pos;

for (int i = pos; i + todelete < m_count; i++) for (int i = pos; i + todelete < m_count; i++)
m_data[i] = m_data[i + todelete]; m_data[i] = m_data[i + todelete];
for (int i = m_count - todelete; i < m_count; i++) for (int i = m_count - todelete; i < m_count; i++)
@@ -197,6 +200,23 @@ public:
m_count -= todelete; m_count -= todelete;
} }


void RemoveSwap(int pos, int todelete = 1)
{
ASSERT(todelete >= 0);
ASSERT(pos - todelete >= -m_count - 1);
ASSERT(pos + todelete <= m_count);
if (pos < 0)
pos = m_count + pos;

for (int i = 0; i < todelete; i++)
{
if (pos + i < m_count - 1 - i)
m_data[pos + i] = m_data[m_count - 1 - i];
m_data[m_count - 1 - i].~Element();
}
m_count -= todelete;
}

void Resize(int count, Element e = Element()) void Resize(int count, Element e = Element())
{ {
ASSERT(count > 0); ASSERT(count > 0);


+ 30
- 0
test/unit/array.cpp View File

@@ -83,9 +83,39 @@ LOLUNIT_FIXTURE(ArrayTest)
a << 0 << 1 << 2 << 3; a << 0 << 1 << 2 << 3;
a.Remove(1); a.Remove(1);


LOLUNIT_ASSERT_EQUAL(a.Count(), 3);
LOLUNIT_ASSERT_EQUAL(a[0], 0); LOLUNIT_ASSERT_EQUAL(a[0], 0);
LOLUNIT_ASSERT_EQUAL(a[1], 2); LOLUNIT_ASSERT_EQUAL(a[1], 2);
LOLUNIT_ASSERT_EQUAL(a[2], 3); LOLUNIT_ASSERT_EQUAL(a[2], 3);

Array<int> b;
b << 0 << 1 << 2 << 3;
b.Remove(-2);

LOLUNIT_ASSERT_EQUAL(b.Count(), 3);
LOLUNIT_ASSERT_EQUAL(b[0], 0);
LOLUNIT_ASSERT_EQUAL(b[1], 1);
LOLUNIT_ASSERT_EQUAL(b[2], 3);
}

LOLUNIT_TEST(ArrayRemoveSwap)
{
Array<int> a;
a << 0 << 1 << 2 << 3;
a.RemoveSwap(1);

LOLUNIT_ASSERT_EQUAL(a.Count(), 3);
LOLUNIT_ASSERT_EQUAL(a[0], 0);
LOLUNIT_ASSERT_EQUAL(a[1], 3);
LOLUNIT_ASSERT_EQUAL(a[2], 2);

Array<int> b;
b << 0 << 1 << 2 << 3;
b.Remove(1, 2);

LOLUNIT_ASSERT_EQUAL(b.Count(), 2);
LOLUNIT_ASSERT_EQUAL(b[0], 0);
LOLUNIT_ASSERT_EQUAL(b[1], 3);
} }
#endif #endif




Loading…
Cancel
Save