ashok
ashok

Reputation: 13

How to sort any vector by value?

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}

Upvotes: 0

Views: 269

Answers (1)

Exagon
Exagon

Reputation: 5098

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);
          });

Upvotes: 4

Related Questions