Using std::ranges::subrange()
and standard iterator pairs both allow you to define a specific portion of a range, but they have different use cases and benefits.
Iterator pairs have been a traditional way to define subranges in C++. You specify a range by providing two iterators: a beginning and an end. This method is straightforward and has been widely used:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
auto begin = vec.begin() + 1;
auto end = vec.begin() + 4;
std::for_each(begin, end, [](int n) {
std::cout << n << ", ";
});
}
2, 3, 4,
std::ranges::subrange
std::ranges::subrange
is part of the C++20 ranges library. It provides a more powerful and expressive way to work with subranges. A subrange
is a view that encapsulates a pair of iterators and can be used with range-based algorithms seamlessly:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
auto subrange = std::ranges::subrange(
vec.begin() + 1, vec.begin() + 4);
std::ranges::for_each(subrange, [](int n) {
std::cout << n << ", "; });
}
2, 3, 4,
std::ranges::subrange
std::ranges::subrange
makes the code more readable and expressive, clearly indicating that you are working with a subrange of a collection.Iterator Pairs is suited for:
std::ranges::subrange
is suited for:
In summary, std::ranges::subrange
offers a modern and powerful alternative to iterator pairs, enhancing code readability and integration with range-based algorithms.
However, iterator pairs remain a valid and useful tool, especially in simpler or performance-critical contexts.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to 8 more useful algorithms from the standard library, and how we can use them alongside views, projections, and other techniques