Yes, std::ranges::subrange
can be used with standard library algorithms that modify the container.
Since std::ranges::subrange
provides non-owning views of containers, you can apply algorithms to modify the elements within the subrange, and these changes will reflect in the original container.
std::ranges::sort()
You can use std::ranges::sort()
to sort elements within a subrange, and the changes will be reflected in the underlying container.
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> Nums{5, 3, 4, 1, 2};
std::ranges::subrange view{
Nums.begin() + 1, Nums.end() - 1};
std::ranges::sort(view);
for (int n : Nums) {
std::cout << n << ", ";
}
}
5, 1, 3, 4, 2,
std::ranges::reverse()
You can also use std::ranges::reverse()
to reverse the elements within a subrange.
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> Nums{1, 2, 3, 4, 5};
std::ranges::subrange view{
Nums.begin() + 1, Nums.end() - 1};
std::ranges::reverse(view);
for (int n : Nums) {
std::cout << n << ", ";
}
}
1, 4, 3, 2, 5,
std::ranges::for_each()
With std::ranges::for_each()
, you can apply a custom function to each element in the subrange, modifying the elements in place.
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
void increment(int& n) { n += 1; }
int main() {
std::vector<int> Nums{1, 2, 3, 4, 5};
std::ranges::subrange view{
Nums.begin(), Nums.end()};
std::ranges::for_each(view, increment);
for (int n : Nums) {
std::cout << n << ", ";
}
}
2, 3, 4, 5, 6,
std::ranges::subrange
works seamlessly with standard library algorithms that modify the container.
By using subranges, you can apply various algorithms to a subset of the container while keeping the changes synchronized with the underlying data.
Answers to questions are automatically generated and may not have been reviewed.
std::ranges::subrange
This lesson introduces std::ranges::subrange, allowing us to create non-owning ranges that view some underlying container