In the following sort function of C++ how the 3rd argument is working?
sort(a.begin(), a.end(), [](int x, int y) { return x % 2 < y % 2; });
# | User | Rating |
---|---|---|
1 | tourist | 3845 |
2 | jiangly | 3707 |
3 | Benq | 3630 |
4 | orzdevinwang | 3573 |
5 | Geothermal | 3569 |
5 | cnnfls_csy | 3569 |
7 | jqdai0815 | 3532 |
8 | ecnerwala | 3501 |
9 | gyh20 | 3447 |
10 | Rebelz | 3409 |
# | User | Contrib. |
---|---|---|
1 | maomao90 | 171 |
2 | adamant | 164 |
3 | awoo | 163 |
4 | TheScrasse | 155 |
5 | nor | 153 |
6 | maroonrk | 152 |
6 | -is-this-fft- | 152 |
8 | Petr | 145 |
9 | pajenegod | 144 |
9 | orz | 144 |
sort(a.begin(), a.end(), [](int x, int y) { return x % 2 < y % 2; });
Name |
---|
During comparison-based sorting, you need a way to figure out an "order", i.e. which element goes before another element. The third argument does that for the case N=2, in comparing the relative order of 2 elements. This function just helps you figure out the order of x and y for any arbitrary x and y. Note that your comparator must follow some basic properties, else you won't get the expected results. Link to very helpful blog
Thanks
You can observe the third argument is sorting the array based on the above results. Since
(even) % 2 < (odd) % 2
, all the even elements will get pushed to left extremity of the array and vice versa for odd elements.Now if you want to preserve the non-decreasing nature on the two counterparts (odd & even) you can modify the function as follows.
That's awesome! Thank you..