[英]How to sort a vector using std::views C++20 feature?
I want to loop through a vector in a sorted way without modifying the underlying vector .我想在不修改基础 vector 的情况下以排序的方式循环遍历 vector 。
Can std::views
and/or std::range
be used for this purpose? std::views
和/或std::range
可以用于此目的吗?
I've successfully implemented filtering using views
, but I don't know if it is possible to sort using a predicate.我已经使用
views
成功实现了过滤,但我不知道是否可以使用谓词进行排序。
You can find an example to complete here: https://godbolt.org/z/cKer8frvq您可以在此处找到要完成的示例: 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.您必须修改某些内容才能使用
std::ranges::sort
(或std::sort
),但它不一定是您的实际数据。
#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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.