Something went wrong. Try again.
A Tour of C++ for experienced programmers, as if C++26 is the only version that ever existed.
Something went wrong. Try again.
123456789101112131415161718192021#include <vector>#include <algorithm>#include <iostream>#include <ranges>#include <cmath>
struct DistanceComparator { int ref; constexpr bool operator()(int a, int b) const { return std::abs(a - ref) < std::abs(b - ref); }};
int main(){ std::vector<int> v = {5,1,3,2,4}; std::ranges::sort(v, DistanceComparator{0}); // sort by distance from 0 (i.e., absolute value) for(int x: v) std::cout << x << ' '; std::cout << std::endl; return 0;}