Char to Int, Sort using my own function

Mar 31, 2015 at 10:42pm
Hi guys,
I've got a string of 3 characters, first 2 are numbers and last one is a letter
I was thinking of pushbacking it to vector <pair <int, char > > v and then sorting it with

bool f1(pair <int,char> a, pair <int,char> b)
{
return a.first < b.first || a.second < b.second;
}

sort(v.begin(),v.end(),f1);

2 questions, can I use that function to sort first through numbers then through letters, and second how do i change first 2 char numbers to an int number?
Mar 31, 2015 at 10:46pm
A "char number" is usually called "digit".

It is not clear, what you should sort.
Mar 31, 2015 at 10:55pm
I tried changeing *digit* to int by int num=(s[0]-'0')*10+(s[1]-'0'); soo, why doesnt that work?

bool f1(pair <int,char> a, pair <int,char> b)
{
return a.second< b.second || a.first < b.first;
}

and sort should work like
10 A
11 B
12 A
14 B
10 B

sorted would look like

10 A
12 A
10 B
11 B
14 B
Mar 31, 2015 at 11:05pm
sorted would look like

Would or should?

Do you want to sort first by the letter and then by the number? You could store "10A" as "A10" and lexicographical sort would do the work for you.

The logic of your f1() ... there are three cases:
1. a<b
2. a==b
3. b<a

The first and last are clearcut: the character alone will rule the order.
Only on case of equality does the lesser member of the pair make a difference.
Mar 31, 2015 at 11:30pm
Thanks dude, helped!
Topic archived. No new replies allowed.