At the input is a certain number of segments, each of which is given by the left and right border. Is it possible to somehow sort the segments (two borders together) by the right border using the built-in sort () / qsort () sorts. I tried to do something with pointers and dynamic arrays, but nothing happened. I understand how to implement this by doing the sorting myself, but I need to get as little code as possible on my part, so I wanted to use the standard sorting.
1 answer
Here is an example of how to sort the segments by the second value and at the same time ensure that with equal second values the first values of the segments will be ordered.
#include <iostream> #include <algorithm> #include <iterator> #include <functional> #include <utility> int main() { std::pair<int, int> a[] = { { 1, 3 }, { 4, 2 }, { 6, 5 }, { 0, 2 }, { 4, 5 } }; std::sort(std::begin(a), std::end(a), [](const auto &a, const auto &b) { return std::tie( a.second, a.first ) < std::tie( b.second, b.first ); }); for (const auto &p : a) { std::cout << "<" << p.first << ", " << p.second << "> "; } std::cout << std::endl; return 0; } Output of the program to the console
<0, 2> <4, 2> <1, 3> <4, 5> <6, 5> If it doesn't matter how the first values of the segments will be ordered, then the functional object for sorting can be simplified.
#include <iostream> #include <algorithm> #include <iterator> #include <utility> int main() { std::pair<int, int> a[] = { { 1, 3 }, { 4, 2 }, { 6, 5 }, { 0, 2 }, { 4, 5 } }; std::sort(std::begin(a), std::end(a), [](const auto &a, const auto &b) { return a.second < b.second; }); for (const auto &p : a) { std::cout << "<" << p.first << ", " << p.second << "> "; } std::cout << std::endl; return 0; } Output of the program to the console
<4, 2> <0, 2> <1, 3> <6, 5> <4, 5> You can notice the difference between the findings of these two programs.
- Thank you very much. I still understand the standard containers. Your answer is completely satisfied. - Fozek
|