Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Several generic standard template library (STL) algorithms, such as std::remove() and std::unique(), remove instances of elements from a container without shrinking the size of the container. Instead, these algorithms return a ForwardIterator to indicate the partition within the container after which elements are no longer valid. The elements in the container that precede the returned iterator are valid elements with specified values, whereas the elements that succeed the returned iterator are valid but have unspecified values. Accessing unspecified values of elements iterated over results in unspecified behavior. Frequently, the erase-remove idiom is used to shrink the size of the container when using these algorithms.

...

In this noncompliant example, the two iterators that delimit the range point into the same container, but the first iterator does not precede the second. On each iteration of its internal loop, std::for_each() compares the first iterator with the second for equality, and as long as they are not equal, it will continue to increment the first iterator. Incrementing the iterator representing the past-the-end element of the range results in undefined behavior.

Code Block
bgColor#FFcccc
langcpp
#include <algorithm>
#include <iostream>
#include <vector>
 
void f(const std::vector<int> &C) {
  std::for_each(C.end(), C.begin(), [](int I) { std::cout << I; });
}

...

In this noncompliant code example, elements matching 42 are removed from the given container. The contents of the container are then printed to the standard output stream. However, if any elements were removed from the container, the range-based for loop iterates over an invalid iterator range, resulting in unspecified behavior.

Code Block
bgColor#ffcccc
langcpp
#include <algorithm>
#include <iostream>
#include <vector>
 
void f(std::vector<int> &C) {
  std::remove(C.begin(), C.end(), 42);
  for (auto V : C) {
    std::cout << "Container element: " << V << std::endl;
  }
}

...

[ISO/IEC 14882-2014]

24, "Iterators Library"
25.3, "Mutating Sequence Operations" 

[Meyers 01]Item 32, " Follow remove-like algorithms with erase if you really want to remove something"

 

...