Modernize for loops
clang-tidy's modernize-loop-convert check helped us find some simple cases that could be converted to C++11 range-based loops. There are some more cases that require manual help. The necessary functions cmMakeRange
and cmReverseRange
are found in the header cmAlgorithms.h
.
Type conversion of the iterator
In this case, begin()
returns a std::vector<std::string>::iterator
, but it is converted to std::vector<std::string>::const_iterator
. This is not found by clang-tidy.
std::vector<std::string> container = ...;
// legacy
typedef std::vector<std::string>::const_iterator It;
for (It it = container.begin(); it != container.end(); ++it) {
// range-based
for (std::string const& str : cmMakeRange(container)) {
Looping backwards
// legacy
for (auto it = container.rbegin(); it != container.rend(); ++it) {
// range-based
for (std::string const& str : cmReverseRange(container)) {
Iterating over a subset
std::sort(container.begin(), container.end());
auto end = std::unique(container.begin(), container.end());
// legacy
for (auto it = container.begin(); it != end; ++it) {
// range-based
for (std::string const& str : cmMakeRange(container.cbegin(), end)) {
Skipping elements at the beginning
// legacy
for (auto it = container.begin() + 2; it != container.end(); ++it) {
// range-based
for (std::string const& str : cmMakeRange(container).advance(2)) {
Skipping elements at the end
// legacy
for (auto it = container.begin(); it + 2 != container.end(); ++it) {
// range-based
for (std::string const& str : cmMakeRange(container).retreat(2)) {