I want to loop through a vector in a sorted way without modifying the underlying vector.
Can std::views and/or std::range be used for this purpose?
I've successfully implemented filtering using views, but I don't know if it is possible to sort using a predicate.
You can find an example to complete here : https://godbolt.org/z/cKer8frvq
#include <iostream>
#include <ranges>
#include <vector>
#include <chrono>
struct Data{
int a;
};
int main() {
std::vector<Data> vec = {{1}, {2}, {3}, {10}, {5}, {6}};
auto sortedView = // <= can we use std::views here ?
for (const auto &sortedData: sortedView) std::cout << std::to_string(sortedData.a) << std::endl; // 1 2 3 5 6 10
for (const auto &data: vec) std::cout << std::to_string(data.a) << std::endl; // 1 2 3 10 5 6
}
You have to modify something to use std::ranges::sort (or std::sort), but it doesn't have to be your actual data.
#include <iostream>
#include <ranges>
#include <numeric>
#include <algorithm>
#include <vector>
#include <chrono>
struct Data{
int a;
friend auto operator<=> (const Data &, const Data &) = default;
};
int main() {
std::vector<Data> vec = {{1}, {2}, {3}, {10}, {5}, {6}};
std::vector<std::size_t> indexes(vec.size());
std::iota(indexes.begin(), indexes.end(), std::size_t{ 0 }); // 0z in C++23
auto proj = [&vec](std::size_t i) -> Data & { return vec[i]; };
std::ranges::sort(indexes, std::less<>{}, proj);
auto sortedView = std::ranges::views::transform(indexes, proj);
for (const auto &sortedData: sortedView) std::cout << sortedData.a << std::endl; // 1 2 3 5 6 10
for (const auto &data: vec) std::cout << data.a << std::endl; // 1 2 3 10 5 6
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With