+ 9
std::sort() has an overload that accepts a comparator function (a lambda will also do the trick).
https://en.cppreference.com/w/cpp/algorithm/sort
You can play around with the comparator function by changing its return value to get the desired output đ
+ 5
Can you write your own sort function?
Try it by using math.abs( v[i] ) , instead of v[i] , when comparing values...
abs() returns numbers absolute value.
Ex: abs(-5) => 5 , abs(5) => 5
+ 3
It's for calculating absolute value of a number.
https://en.cppreference.com/w/cpp/numeric/math/abs
+ 3
i personally upvote the advice to use std::sort overloading because implementing sorting algorithms manually is a big pain & usually not that effective if you're not really into this topic
+ 3
Mirielle
I made a modification to your code. Used template for more flexibility and tweaked the lambda so that negative values are placed to the left when there are repeated absolute numbers. It adds an additional level of sorting, I think.
https://code.sololearn.com/cLyQJ05Sgsh6/?ref=app
+ 2
Manav Roy
No. It yields positive value, but not change original. If you want to change, you can change by
num = abs(num) ;
+ 2
Manav Roy
it's a lambda expression. Think of it as an anonymous function.Here it is used to modify the behavior of sort().
https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=msvc-170
+ 1
Mirielle
The fact that we can code on the phone is amazing in itself.
But yes, typing is a challenge.
That's why my secret weapon is a Bluetooth external keyboardđ
.
Maybe someday we'll have AI enhanced ide, where we would just copy and paste the problem and the code would be auto generated...
Tools like Kite and TabNine are available for quite some time already.
+ 1
why you can't just code on a pc? or you don't have one