Convenient and readable way of removing an element from std::vector

103 Views Asked by At

I need to erase/remove an element from a std::vector.

I know that this can be done with myvector.erase(myvector.begin() + index) but this looks ugly to me.

Something like myvector.removeindex(index) would be so much more readable.

Do they plan something like that in C++20 or in C++23 ?

1

There are 1 best solutions below

2
Nicol Bolas On

Both C++20 and C++23 are finished, so there are no "plans" to do anything in them. And there are no proposals for C++26 to add this function.

Nor is there a likelihood that such a trivial proposal would be accepted. Containers are meant to use iterator-based interfaces. Converting an index into an iterator for a random access container is pretty trivial, so there is no compelling reason to create a specialized function.

But if you really want, you can make your own free function that, through concepts, works on any random access range that you can erase from:

template<std::ranges::random_access_range T>
  requires requires(T &t) {t.erase(std::ranges::begin(t));}
constexpr auto remove_index(T &t, std::ranges::range_difference_t<T> ix)
{
  return t.erase(std::ranges::begin(t) + ix);
}