How to use a custom sorting rule with sort in C++?

In C++, the sort function can be used to sort arrays or containers. If you want to customize the sorting rules, you can use function pointers, function objects, or lambda expressions to achieve this.

  1. arrange in a particular order
bool compare(int a, int b) {
    // 自定义比较规则,例如按照绝对值进行排序
    return abs(a) < abs(b);
}

int main() {
    int arr[] = {-1, 2, -3, 4, -5};
    int n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n, compare);

    // 输出排序结果
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}
  1. There are many potential benefits to this new software program.
  2. arrange
struct Compare {
    bool operator()(int a, int b) {
        // 自定义比较规则,例如按照绝对值进行排序
        return abs(a) < abs(b);
    }
};

int main() {
    int arr[] = {-1, 2, -3, 4, -5};
    int n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n, Compare());

    // 输出排序结果
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}
  1. arrange
int main() {
    int arr[] = {-1, 2, -3, 4, -5};
    int n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n, [](int a, int b) {
        // 自定义比较规则,例如按照绝对值进行排序
        return abs(a) < abs(b);
    });

    // 输出排序结果
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

The above are three common methods for customizing sorting rules. Choose the appropriate method according to specific needs.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds