...
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 (after incrementing it) with the second for equality, and as ; 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.
...
In this compliant solution, the iterator values passed to std::for_each()
are passed in the proper order:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <algorithm> #include <iostream> #include <vector> void f(const std::vector<int> &c) { std::for_each(c.begin(), c.end(), [](int i) { std::cout << i; }); } |
...
In this compliant solution, the proper iterator generated by a call to end()
is passed:.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <algorithm> #include <iostream> #include <vector> void f(const std::vector<int> &c) { std::for_each(c.begin(), c.end(), [](int i) { std::cout << i; }); } |
...
[ISO/IEC 14882-2014] | Clause 24, "Iterators Library" |
[Meyers 01] | Item 32, "Follow Remove-like Like Algorithms with erase If You Really Want to Remove Something" |
...