Блог пользователя TryOmar

Автор TryOmar, история, 15 месяцев назад, По-английски

Let's say you have a set of integers called nums, and you want to sort them based on certain criteria, such as frequency and value. Here's a brief code snippet demonstrating how you can achieve this:

const int N = 1e5 + 1;
int fr[N] = {};

// Define a custom sorting criterion
struct sortCri {
    bool operator()(int a, int b) const {
        // Customize the sorting order here
        if (fr[a] == fr[b]) return a > b;  // Sort values in descending order
        else return fr[a] < fr[b];         // Sort frequencies in ascending order
    }
};

// Create a set using the custom sorting criterion
set<int, sortCri> nums;

In the code above, we have a set called nums that will sort elements based on the criteria defined in the sortCri struct. In this example, we sort in ascending order of frequency (fr[a]) and in descending order of values (a).

You can easily adapt this code to your specific sorting requirements by modifying the conditions inside the operator() function within the sortCri struct.

  • Проголосовать: нравится
  • +16
  • Проголосовать: не нравится

»
15 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Thanks for sharing these information!

»
15 месяцев назад, # |
Rev. 5   Проголосовать: нравится +3 Проголосовать: не нравится

Use lambda to make the code shorter:

set<int, decltype([](int a, int b) { return fr[a] == fr[b] ? a > b : fr[a] < fr[b]; })> nums;

I like lambda :)