iamdumb's blog

By iamdumb, history, 9 years ago, In English

This might be very vague,stupid and nonsense question but I want to ask.I have learnt how to make own Comparators.So can anybody please mention some links of question which can require to make our own comparetor function :)

  • Vote: I like it
  • +3
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it +5 Vote: I do not like it

comparators are basically boolean functions which like you think, are used for comparing data on basis of a parameter. they can be used in a variety of places, where ordering of data is done on basis of a parameter (eg sorting)

lets take std::sort() in C++. By default, it sorts data in ascending order. Suppose you want to sort a list of numbers on the basis of count of digit '5' in them in ascending order. For convenience of this task, we take numbers as a string and write comparator for the sort function

code

// in name of God
#include <bits/stdc++.h>
using namespace std;

int countFive(string number)
{
    int cnt = 0;
    for(int i = 0; i < number.size(); i++)
        if(number[i] == '5')
            cnt++;
    return cnt;
}

bool comparator(string a,string b)
{
    if(countFive(a) < countFive(b))
        return true;
    return false;
}

int main(void)
{
    freopen("input.txt","r",stdin);
    int n;
    cin >> n;
    string numbers[n];
    for(int i = 0; i < n; i++)
        cin >> numbers[i];
    sort(numbers,numbers+n,comparator);
    for(int i = 0; i < n; i++)
        cout << numbers[i] << ' ';
    return 0;
}

sorry for weak english and c++ isnt my primary language

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

uva use next_permutation with an appropriate comparator function

also it is useful to learn how to define comparators for data structures like maps and sets you can see this if you are interested