Add wxVector::insert() overload taking count of items to insert

Generalize the existing insert() to be more compatible with std::vector.
This commit is contained in:
Vadim Zeitlin
2017-11-18 16:36:41 +01:00
parent 25a7c70631
commit 8246c922af
3 changed files with 31 additions and 6 deletions

View File

@@ -442,14 +442,14 @@ public:
const_reverse_iterator rbegin() const { return const_reverse_iterator(end() - 1); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin() - 1); }
iterator insert(iterator it, const value_type& v = value_type())
iterator insert(iterator it, size_type count, const value_type& v)
{
// NB: this must be done before reserve(), because reserve()
// invalidates iterators!
const size_t idx = it - begin();
const size_t after = end() - it;
reserve(size() + 1);
reserve(size() + count);
// the place where the new element is going to be inserted
value_type * const place = m_values + idx;
@@ -457,27 +457,33 @@ public:
// unless we're inserting at the end, move following elements out of
// the way:
if ( after > 0 )
Ops::MemmoveForward(place + 1, place, after);
Ops::MemmoveForward(place + count, place, after);
// if the ctor called below throws an exception, we need to move all
// the elements back to their original positions in m_values
wxScopeGuard moveBack = wxMakeGuard(
Ops::MemmoveBackward, place, place + 1, after);
Ops::MemmoveBackward, place, place + count, after);
if ( !after )
moveBack.Dismiss();
// use placement new to initialize new object in preallocated place in
// m_values and store 'v' in it:
::new(place) value_type(v);
for ( size_type i = 0; i < count; i++ )
::new(place + i) value_type(v);
// now that we did successfully add the new element, increment the size
// and disable moving the items back
moveBack.Dismiss();
m_size++;
m_size += count;
return begin() + idx;
}
iterator insert(iterator it, const value_type& v = value_type())
{
return insert(it, 1, v);
}
iterator erase(iterator it)
{
return erase(it, it + 1);

View File

@@ -194,6 +194,15 @@ public:
*/
iterator insert(iterator it, const value_type& v = value_type());
/**
Insert the given number of copies of @a v at the given position.
@return Iterator for the first inserted item.
@since 3.1.1
*/
iterator insert(iterator it, size_type count, const value_type& v);
/**
Assignment operator.
*/

View File

@@ -162,6 +162,16 @@ void VectorsTestCase::Insert()
CPPUNIT_ASSERT( v[1] == 'a' );
CPPUNIT_ASSERT( v[2] == 'X' );
CPPUNIT_ASSERT( v[3] == 'b' );
v.insert(v.begin() + 3, 3, 'Z');
REQUIRE( v.size() == 7 );
CHECK( v[0] == '0' );
CHECK( v[1] == 'a' );
CHECK( v[2] == 'X' );
CHECK( v[3] == 'Z' );
CHECK( v[4] == 'Z' );
CHECK( v[5] == 'Z' );
CHECK( v[6] == 'b' );
}
void VectorsTestCase::Erase()