Пожалуйста, подпишитесь на официальный канал Codeforces в Telegram по ссылке https://t.me/codeforces_official. ×

Custom Sorting in C++ Set Container

Правка en1, от TryOmar, 2023-09-10 17:06:13

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.

Теги c++ stl, sort, set, custom sort, opeartor overload

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский TryOmar 2023-09-10 17:06:13 1082 Initial revision (published)