Gabriel
Gabriel

Reputation: 3077

How do I replace a range with another range in a vector?

I want to replace a range of elements in a vector by a single other element (built from that range, but it doesn't matter). I'd like to do so without erasing first and inserting then, for all subsequent elements would me moved twice.

I figured we could generalize that with the replacement of a range by another range, whatever their sizes. Replace an empty range with something and you get insert. Replace something with an empty range and you get erase.

Anyways replace seems not to do that. It replaces all or some elements in a rage with copies of the given element. No moving around.

swap_ranges swaps elements one by one, no erase or insert either.

Have I missed an algorithm for that? Maybe a member function?

Maybe I should use list then?

Upvotes: 1

Views: 444

Answers (2)

eerorika
eerorika

Reputation: 238311

I want to replace a range of elements in a vector by a single other element

As far as I know, there is no algorithm for this in standard library. But it can be fairly simply be built on top of the existing ones: Remove all except first of the range. Assign the element that wasn't removed. In the special case of empty range, insert instead of assigning. Return iterator to the beginning of the removed elements (iterator to end in case nothing was removed) so that the caller can erase them.

I figured we could generalize that with the replacement of a range by another range

This works pretty much the same as the single insert variation, but is more complex. Replace assignment with std::copy, and take into consideration that there is also a case where you both assign (copy) and insert a subrange depending on lengths of the input ranges.

The order assignment, remove, insert does not matter.

Upvotes: 1

Marshall Clow
Marshall Clow

Reputation: 16670

This is an algorithm that can't be done with "just iterators". To change the size of the underlying sequence, you need to be able to call insert or erase on the underlying container.

So even though you might want to write something like:

template <typename Iter1, typename Iter2>
void replaceRange (Iter1 s_first, Iter1 s_last, Iter2 d_first, Iter2 d_last);

it won't ever work (except for the cases where the sizes are the same)

Upvotes: 1

Related Questions