Search code examples
c++erasestdarray

Erase element from std array


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?


Solution

  • 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.