darray: add insert_n overload

This commit is contained in:
Danny Robson 2018-11-08 14:11:00 +11:00
parent f44c7d5b46
commit 26edf25b82
2 changed files with 53 additions and 22 deletions

View File

@ -103,15 +103,28 @@ namespace cruft {
--m_size;
}
void insert (iterator pos, ValueT const &val)
/// Insert one copy of `value' before `pos'
iterator insert (iterator pos, ValueT const &val)
{
return insert (pos, 1u, val);
}
/// Insert `count' copies of `value' before `pos'.
iterator insert (const_iterator pos, size_type count, ValueT const &val)
{
// Ensure we have enough space
CHECK_LIMIT (pos, begin (), end ());
CHECK_LT (m_size, CapacityV);
CHECK_LE (m_size, CapacityV - count);
*pos = val;
std::move_backward (pos, cend (), end () + count);
m_size += count;
for (auto cursor = pos + 1; cursor != end (); ++cursor)
*cursor = *(cursor - 1);
auto dst = const_cast<iterator> (pos);
std::fill_n (dst, count, val);
return dst;
}

View File

@ -6,6 +6,7 @@ main (int, char**)
{
cruft::TAP::logger tap;
{
cruft::darray<8,int> val ({ 0, 1, 2, 3, 4, 5, 6, 7});
tap.expect_eq (val.size (), 8u, "query for size");
@ -26,9 +27,26 @@ main (int, char**)
}
{
val.insert (val.begin () + 4, 9);
tap.expect_eq (val[5], 9, "inserted values matches indexed value");
// Try inserting a value and see if it sticks.
//
// Ensure that a unique value is used here.
// Perform an accumulate to check the rest of the values are there too.
val.insert (val.begin () + 4, 13);
tap.expect_eq (val[4], 13, "inserted values matches indexed value");
auto const sum = std::accumulate (val.cbegin (), val.cend (), 0u);
tap.expect_eq (sum, 39u, "accumulate over new array suggests all still present");
}
}
{
cruft::darray<8,int> val ({ 0, 1, 2, 3 });
cruft::darray<8,int> const res ({ 0, 1, 13, 13, 13, 2, 3 });
val.insert (val.begin () + 2, 3, 13);
tap.expect_eq (val, res, "trivial insert_n");
}
return tap.status ();
}