问问题
35 次
1 回答
1
You need to specify a comparison for T
if std::less<T>
is unavailable.
Both std::sort
and std::ranges::sort
require a strict weak ordering predicate, not operator<=>
(but that can supply one, via <
and std::less
)
template<typename T>
bool complex_less (std::complex<T> lhs, std::complex<T> rhs) { return abs(lhs) < abs(rhs); };
int main() {
auto things = std::vector<thing>{{9, 10}, {7, 8}, {3, 4}, {1, 2}, {5, 6}};
std::sort(things.begin(), things.end());
std::ranges::sort(things);
std::ranges::sort(things, {}, [](const auto& e) { return e.sum(); });
std::ranges::sort(things, [](const auto& a, const auto& b) { return a < b; }, {});
std::ranges::sort(things, {}, &thing::x);
std::ranges::sort(things, {}, static_cast<int (thing::*)()>(&thing::sum)); // need cast to disambiguate pointer-to-member
for (const auto& e: things) std::cout << e << " ";
std::cout << "\n";
auto complexes = std::vector<std::complex<double>>{{9, 10}, {7, 8}, {3, 4}, {1, 2}, {5, 6}};
std::sort(complexes.begin(), complexes.end(), complex_less<double>); // fine
std::ranges::sort(complexes, complex_less<double>); // also fine
std::ranges::sort(complexes, {}, [](const auto& c) { return std::abs(c); }); // still fine
std::ranges::sort(complexes, {}, [](const auto& c) { return c.real(); }); // fine
for (const auto& e: complexes) std::cout << e << " ";
std::cout << "\n";
return EXIT_SUCCESS;
}
于 2022-02-08T14:27:39.863 回答