For simple sorting in C++, sort() method is used of algorithm header.
e.g.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n;
cin>>n;
vector<int> a;
int t;
for(int i=0; i<n; i++)
{
cin>>t;
a.push_back(t);
}
sort(a.begin(), a.end());
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
}
Input:
5
4 8 9 2 1
Output:
1 2 4 8 9
But for advanced sorting, where structures would be sorted based upon its one of the element, we need to create a method compare to guide the sort method. Check it out below:
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
struct node {
int value;
int key;
};
bool compare(const node& a, const node& b) {
return a.key < b.key;
}
int main() {
int n;
cin >> n;
vector<node> a;
int t1, t2;
for (int i = 0; i < n; i++) {
cin >> t1 >> t2;
node t3;
t3.value = t1;
t3.key = t2;
a.push_back(t3);
}
sort(a.begin(), a.end(), compare);
for (int i = 0; i < n; i++)
{
cout << a[i].value << " "<<a[i].key<<endl;
}
}
Input:
5
4 7
7 4
2 5
9 6
3 8
Output:
7 4
2 5
9 6
4 7
3 8
So, you can check out that the nodes are sorted based upon its "key" variable.
In the similar way, you can sort the pairs based upon its "first" variable or "second" variable, whichever you do want.