In C++, the erase-remove idiom is a great way to delete all elements of a standard container that satisfy a given criterion.
Is it possible to extend the erase-remove idiom to work on multiple containers at once?
That is, can one invoke something similar to erase-remove
on one container, and have the corresponding elements in another container removed as well?
In my particular case, the containers are all std::vectors
of the same size.
For example, if elements 0
, 3
, and 5
are deleted from the first container, I would like elements 0
, 3
, and 5
deleted from the second container as well.
One could, for example, precompute a container that flags the elements to be deleted, build a predicate for remove_if
that simply indexes into the flag container, and invoke erase-remove
multiple times.
Is it possible to do what I want, without the precomputation?
Yes you can do this. It works as is. I provide an example code and explain on it.
In this code we want to delete
5
from vectorv
and we usestd::remove
andstd::erase
afterwards. You have to understand what doesstd::remove
do.std::remove
swaps elements in container a way that all elements to be deleted go to the end and this function returns an iterator to the first element to be deleted. Nextstd::erase
takes this iterator and removes all elements beginning from this iterator and till the end of a container (actually till the second argument.v.end()
in our case).This code does exactly what you need.