Converting std::ranges::subrange
to Original Container Type
How can I convert a std::ranges::subrange
back to its original container type?
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:
Using Standard Algorithms
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,
Creating a Container Directly
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,
Using std::vector
Constructor
If 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,
Choosing the Right Method
- Use
std::ranges::copy()
for flexibility with various containers. - Use range-based constructors for simplicity and direct initialization.
By converting a std::ranges::subrange
back to a container, you can easily manipulate the data as needed in your programs.
Creating Views using std::ranges::subrange
This lesson introduces std::ranges::subrange, allowing us to create non-owning ranges that view some underlying container