浏览代码

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 年前
父节点
当前提交
ef0bd031ab
共有 2 个文件被更改,包括 51 次插入1 次删除
  1. +21
    -1
      src/lol/base/array.h
  2. +30
    -0
      test/unit/array.cpp

+ 21
- 1
src/lol/base/array.h 查看文件

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

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

for (int i = pos; i + todelete < m_count; i++)
m_data[i] = m_data[i + todelete];
for (int i = m_count - todelete; i < m_count; i++)
@@ -197,6 +200,23 @@ public:
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())
{
ASSERT(count > 0);


+ 30
- 0
test/unit/array.cpp 查看文件

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

LOLUNIT_ASSERT_EQUAL(a.Count(), 3);
LOLUNIT_ASSERT_EQUAL(a[0], 0);
LOLUNIT_ASSERT_EQUAL(a[1], 2);
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



正在加载...
取消
保存