Home > Back-end >  How to sort any vector by value?
How to sort any vector by value?

Time:11-10

How to sort a vector by absolute value in c ?

suppose a vector {-10, 12, -20, -8, 15}

output should be {-8, -10, 12, 15, -20}

CodePudding user response:

My guess is that you want to sort the vector by absolute value. You can sort a vector with std::sort in any way you want by passing a lambda to it. The absolute value of an integer can be calulated using std::abs.

std::sort(std::begin(vec), std::end(vec),
          [](const auto& lhs, const auto& rhs){
              return std::abs(lhs) < std::abs(rhs);
          });
  • Related