DEV Community

Sachin 👨🏻‍💻
Sachin 👨🏻‍💻

Posted on

Custom Sort in C++ vs Python (With and Without Lambda Functions)

Custom Sort in C++ v/s Custom Sort in Python3

Eg: Sorting a list of tuples where sorting is to be done in descending order of the second value of the tuple.

IN C++

//header files above
bool compare(pair<int, int> a, pair<int, int> b) {
    return a.second > b.second;
}

int main() {
    vector<pair<int, int>> arr; // a list of tuples
    // Method 1 (With lambda function - C++11 onwards)
    sort(arr.begin(), arr.end(), [&](pair<int, int> a, pair<int, int> b) {
        return a.second > b.second;
    }); 
    // Method 2 (Without lambda function)
    sort(arr.begin(), arr.end(), compare);
}

IN PYTHON3

a = [(1, 2), (2, 3), (3, 4), (4, 5)];

def compare(x):
    return -x[1]

# Method 1 (With lambda function)
sorted_a = sorted(a, key=lambda x: -x[1]) #can also use : sorted(a, lambda x: x[1], reverse=True)

# Method 2 (Without lambda function)
sorted_a = sorted(a, key=compare)

Top comments (0)