Preview: C++23 enumerate and zip
Two useful views for iterating over containers and enumerate
and zip
. These
were introduced in C++23 and are defined in the <ranges>
header.
enumerate
#include <iostream>
#include <vector>
#include <ranges>
int main() {
std::vector<double> powers{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024};
for (auto [index, value] : std::views::enumerate(powers)) {
std::cout << index << " : " << value << std::endl;
}
}
Note that enumerate
returns a reference to the data even if you add const
before
the auto
.
zip
#include <iostream>
#include <vector>
#include <string>
#include <ranges>
int main() {
std::vector<std::string> names{"A", "B", "C", "D", "E"};
std::vector<int> values{1, 2, 3, 4, 5, 6};
for (auto [v, n] : std::views::zip(names, values)) {
std::cout << v << " : " << n << std::endl;
}
}
In this example, the two containers are not the same length, so the looping ends when the first container runs out of objects.