Creating a sliding window view over a data range can be achieved using custom iterators or by leveraging existing libraries. C++20 does not provide a built-in sliding window view, but we can create one using a custom view.
Here's a basic implementation of a sliding window view:
#include <iostream>
#include <ranges>
#include <vector>
template <typename T>
class SlidingWindowView
: public std::ranges::view_base {
public:
SlidingWindowView(
std::vector<T>& data,
std::size_t window_size
) : data_(data), window_size_(window_size) {}
auto begin() const {
return Iterator{data_, 0, window_size_};
}
auto end() const {
return Iterator{
data_,
data_.size() - window_size_ + 1,
window_size_
};
}
private:
std::vector<T>& data_;
std::size_t window_size_;
class Iterator {/*...*/};
};
int main() {
std::vector<int> Numbers{
1, 2, 3, 4, 5, 6, 7, 8, 9};
SlidingWindowView<int> view(Numbers, 3);
for (auto window : view) {
for (int Num : window) {
std::cout << Num << " ";
}
std::cout << "\n";
}
}
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
SlidingWindowView
: A custom view class that takes a data vector and window size.begin()
and end()
: Define the range of the sliding window.The Range-V3 library offers a sliding
view which simplifies the creation of sliding windows:
#include <iostream>
#include <range/v3/view/sliding.hpp>
#include <vector>
int main() {
std::vector<int> Numbers{1, 2, 3, 4, 5, 6, 7, 8, 9};
auto view = Numbers | ranges::views::sliding(3);
for (const auto& window : view) {
for (int Num : window) {
std::cout << Num << " ";
}
std::cout << "\n";
}
}
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
views::sliding
: Provides a built-in sliding view, simplifying window creation.Sliding window views enable powerful data processing techniques, allowing for efficient analysis and manipulation of data in contiguous subranges.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create and use views in C++ using examples from std::views