wannbegood's blog

By wannbegood, history, 4 years ago, In English
#include <bits/stdc++.h>

using namespace std;

bool comp(const int &a , const int&b)
{
    return ((a > 0 and b > 0) ? true : ((a == 0) ? false : true));
}


int32_t main()
{
    vector <int> a = {1 , 0 , 0 , 3 , 12};
    sort(a.begin() , a.end() , comp);
    for(int &x : a)
        cout << x << ", " ;
    cout << endl;
    return 0;
}

The aim is to move all the zeroes to the back keeping the relative order of all other non-zero elements intact. I thought the comparator would do the job as it changes the relative order of two elements a and b if a is equal to 0 and not in any other case, and print the final output as :

0, 0, 1, 3, 12,

However, it printed this :

12, 3, 1, 0, 0,

Why is the comparator failing?

THIS REALLY HELPED : Custom Comparators

Full text and comments »

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

By wannbegood, history, 4 years ago, In English
#include <bits/stdc++.h>

using namespace std;

#define endl '\n'
#define int long long

const int N = 1e5 + 20;

int m[N];

struct comp {
    bool operator() (const pair <int , int> &lhs, const pair <int , int> &rhs) const {
        return lhs.first > rhs.first;
    }
};


int32_t main()
{
    ios_base :: sync_with_stdio(0);
    cin.tie(0);

    set <pair <int , int> , comp> s;
    s.insert({1 , 1});
    s.insert({1 , 2});
    s.insert({1 , 3});
    s.insert({1 , 4});

    for(auto x : s)
        cout << "(" << x.first << "," << x.second << ")  ";
    cout << endl;
    return 0;
}


I expected the above code to print : (1,4) (1,3) (1,2) (1,1) But it only prints :

(1,1)

However, that works fine without the comparator. Why is this strange thing happening?

Full text and comments »

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