2

Is it possible to erase a particular element pointed to by iterator from std array? I know that std vector offers the erase() method. Can the same logic be implemented for std array as well?

Vinod
  • 925
  • 8
  • 9
  • 1
    You cannot delete an element of a statically sized array. Possible duplicate: https://stackoverflow.com/questions/879603/remove-an-array-element-and-shift-the-remaining-ones – mfnx Aug 05 '19 at 10:19
  • 1
    The documentation for [`std::array`](https://en.cppreference.com/w/cpp/container/array) is freely available - you can see all the methods, and the fact that the size is fixed at compile time. If you mean something by "erase" that you can implement with that interface, then go for it. – Useless Aug 05 '19 at 10:23
  • Possible duplicate of [std::vector versus std::array in C++](https://stackoverflow.com/questions/4424579/stdvector-versus-stdarray-in-c) – Raedwald Aug 05 '19 at 10:38

1 Answers1

5

By definition, std::array has a fixed size, so it cannot offer any methods that would change the size.

However, you can still use one of the remove algorithms. These algorithms will not actually remove any elements, but instead only move them to the end of the sequence, so that all "removed" elements fall behind a certain boundary in your range. This boundary is returned as an iterator.

Example:

std::array<int, 4> arr = {0, 1, 2, 3};
auto newEnd = std::remove(arr.begin(), arr.end(), 2);
for (auto iter = arr.begin(); iter != newEnd; ++iter)
    std::cout << *iter << "\n";

See a live example here.

But again, it is important to understand that nothing will be removed from arr. It's only that the range given by arr.begin() and newEnd does not contain any 2 anymore. For an std::vector you could use this newEnd iterator now, to actually remove everything behind and thus alter the vector's size. For std::array you cannot do this.

sebrockm
  • 5,733
  • 2
  • 16
  • 39