Difference between sort(begin(),end()) and sort(begin(),end(),compare)

what is the exact difference between them?

Suppose your objects are pair of integers .

Now given an array of objects : (1,6) , (2,4) , (1,1) , (3,1) , (1,30) , (2,2) .

You can define multiple ways of comparing these objects .

  1. You may say first value decides order , in case first value is same , then second value decides order .

Sorted Array : (1,1) , (1,6) , (1,30) , (2,2) , (2,4) , (3,1)

  1. You may say sum of the elements decides which pair is bigger . In case sum is same the first elements decides order .

Sorted Array : (1,1) , (2,2) , (3,1) , (2,4) , (1,6) , (1,30) .

  1. You may say product of elements decides which pair is bigger . In case product is same the first element decides order .

Sorted Array : (1,1) , (3,1) , (2,2) , (1,6) , (2,4) , (1,30)

Since multiple ways of comparing the elements is possible hence there exists sort functions which take comparator functions to be used for comparing elements . In case comparator function is not specified the normal sort order of the class is followed .

3 Likes

std::sort(begin(),end()) will always sort the passed container in increasing order but suppose you want to sort in some other order say decreasing order, you can do this by writhing a compare function or lambda that will do this for you
example:

struct compare
{

template
bool operator()(T const &a, T const &b) const { return a > b; }
};

std::sort(vec.begin(), vec.end(), compare());