-4
#include<cstdio>
 #include<vector>
 #include<algorithm>
using namespace std;

 struct myclass
{
    bool operator()(pair<int,int> &left, pair<int,int> &right)
    {
        return (left.first < right.first);
    }
 } x;

int main()
{
     int i;
     vector<pair<int,int> > a;
    a.push_back(make_pair(1,2));
    a.push_back(make_pair(1,0));
    a.push_back(make_pair(2,2));
    a.push_back(make_pair(2,1));
     a.push_back(make_pair(3,2));
    a.push_back(make_pair(1,5));

sort(a.begin(),a.end(),x);
for(i=0;i<6;i++)
{
    printf("%d %d\n",a[i].first,a[i].second);
}
return 0;
}

what is the problem with my code sorting vector of pairs by first element ? It is giving [Error] expected primary-expression before 'x' .

1 Answers1

1

Live example.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
using IntPair = pair<int, int>;

int main()
{
    vector<IntPair> a = {
        make_pair(1,2),
        make_pair(1,0),
        make_pair(2,2),
        make_pair(2,1),
        make_pair(3,2),
        make_pair(1,5)
    };

    sort(a.begin(), a.end(), [](const IntPair &left, const IntPair &right)
         {
             return (left.first < right.first);
         });

    for(auto const & i : a)
    {
        cout << i.first << ' ' << i.second << '\n';
    }
}

You don't need the class you have defined nor the global variable x. With modern C++, you don't have to define a functionoid or a functor explicitly, just use a lambda.

legends2k
  • 31,634
  • 25
  • 118
  • 222