Converting a std::ranges::subrange
back to its original container type involves creating a new container and copying the elements from the subrange. This is useful when you need to manipulate or store the data in a different context. Here’s how you can do it:
You can use standard algorithms like std::copy()
to copy elements from the subrange to a new container. Here’s an example using a std::vector
:
#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::vector<int> NewContainer;
std::ranges::copy(View,
std::back_inserter(NewContainer));
for (int n : NewContainer) {
std::cout << n << ", ";
}
}
2, 3, 4,
You can also initialize a container directly from the iterators of the subrange. This approach is concise and leverages the container’s range constructor.
#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::vector<int> NewContainer(
View.begin(), View.end());
for (int n : NewContainer) {
std::cout << n << ", ";
}
}
2, 3, 4,
std::vector
ConstructorIf you’re dealing specifically with std::vector
, you can create a new vector from the subrange using its constructor:
#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::vector<int> NewContainer{
View.begin(), View.end()};
for (int n : NewContainer) {
std::cout << n << ", ";
}
}
2, 3, 4,
std::ranges::copy()
for flexibility with various containers.By converting a std::ranges::subrange
back to a container, you can easily manipulate the data as needed in your programs.
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