Sort vector pair of <int,char>

sort a vector pair >>>6 K 3 T 6 J (FIRST PREFRENCE TO NUMBERS THEN TO CHAR IN ASCENDING ORDER )
AFTER SORTING >>(3 T)( 6 J) (6 K)
I Just learned vector pair today so I am not able to think much … and these questions repeat very often .
Can someone please help me ?

Please format your code - the forum software has mangled it and it won’t compile! :slight_smile:

1 Like

From what I can decipher, this approach should work just fine - so I need to see the real code in order to see what’s wrong.

2 Likes

write your code inside this “`” then close is by same. 3 times before code and 3 times after code. Example

#include<iostream>
using namespace std;
int main(){
  cout<<"Hello, World!"<<endl;
  return 0;
}```
This makes your code readable.

This bit of code should suffice.

#include<bits/stdc++.h>
using namespace std;

bool comp(pair<int,char> p1, pair<int,char> p2)
{
   if(p1.first == p2.first)  return p1.second < p2.second;
   return p1.first < p2.first;

}

int main()
{
   vector < pair < int , char > >  v;
   v.push_back ( make_pair ( 6 , 'K' ) ) ;
   v.push_back ( make_pair ( 3 , 'T' ) ) ;
   v.push_back ( make_pair ( 6 , 'J' ) ) ;
   sort ( v.begin() , v.end() , comp) ;
}

2 Likes

Simply using

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

(as in the OP’s original code sample) should work - this is just duplicating what operator< for std::pair does by default :slight_smile:

Edit:

it also gives the incorrect result due to the use of operator= instead of operator== here:

 if(p1.first = p2.first)  return p1.second < p2.second;

Passing p1 and p2 as reference-to-const would have eliminated the possibility of this error, as well as likely being more efficient :slight_smile:

Edit:

In short, just use:

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

using namespace std;

int main()
{
   vector<pair<int, char>>  v;
   v.push_back ( { 6 , 'K' } ) ;
   v.push_back ( { 3 , 'T' } ) ;
   v.push_back ( { 6 , 'J' } ) ;
   sort ( v.begin() , v.end() ) ;

   for (const auto& [number, letter] : v) // Using structured bindings (C++17 only).
   {
       cout << "(" << number << " " << letter << ")";
   }
}

(I’ve used a C++17 feature just for the printing, but it’s easy to port this to earlier versions of C++).

2 Likes