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
}
std::to_string
is unneded,std::cout << data.a
is correct. – Asta