i need to order a set of pairs (one is int, the second one is char), and i need to have my set ordered like this: 12 G, 11 F, 10 A, 10 B, 10 C (in descending order by first, and in ascending order by second) firstly. this is what i've tried so far, and i get some errors:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <utility>
#include <set>
using namespace std;
set <pair <int,char> > s;
bool myfunction( const pair<int, char>& i, const pair<int, char>& j ) {
if( i.first < j.first ) return false;
if( j.first < i.first ) return true;
return j.second < i.second;
}
void writes()
{ set <pair<int,char> >::iterator it;
for (it = s.begin();it<= s.end();it++) /// line (18)
cout<<(*it).second<<" "<<(*it).first<<"\n\n";
}
int main()
{ ifstream f("info.in");
int n;
f>>n;
for (int i=1;i<=n;i++)
{ pair<int,char> x;
int st;
char nd;
f>>st;
f>>nd;
x.first=st;
x.second=nd;
s.insert(x);
}
writes();
}
first error i get is at line (18) : no match for 'operator<=' (operand types are 'std::set >::.....
your help is greatly appreciated
my input file looks like this:
5
10 B
10 A
10 C
11 F
12 G
@Sam Varshavchik, thanks! that solved my problem with the errors. But still, i don't get the output i needed. I only get:
10 A
10 B
10 C
11 F
12 G
is it possible to change the order criteria in a pair ? if not, what would you recommend to use instead?
it looks like myfunction for the ordering criteria is still ignored by the program. how cand i overload it inside my pair? it looks like, it just sits there and it's never used. the program does it job regardless
i've also tried this: Using custom std::set comparator but it's still not working
using namespace std;
struct lex_compare {
bool operator()(const pair<int, char>& i, const pair<int, char>& j )
{
if( i.first != j.first )
{
return (i.first > j.first);
}
return (j.second > i.second);
}
} // forgot ";", after adding it, it works perfectly.
set <pair <int,char>, lex_compare > s; ///line (22)
void writes()
{ set <pair<int,char> >::iterator it;
for (it = s.begin();it!= s.end();it++) /// line (18)
cout<<(*it).second<<" "<<(*it).first<<"\n\n";
}
int main()
{ ifstream f("info.in");
int n;
f>>n;
for (int i=1;i<=n;i++)
{ pair<int,char> x;
int st;
char nd;
f>>st;
f>>nd;
x.first=st;
x.second=nd;
s.insert(x);
}
writes();
}
ERROR: line (22): invalid declarator before 's';