Custom Sort Method for STL Pair Template

C++C++Beginner
Practice Now

Introduction

In this lab, you will learn how to create a custom sort method for a pair template and implement it using a vector in C++ programming language. This lab assumes that you have prior knowledge of the basics of C++ programming and the concept of the pair template. If you are new to these topics, it is recommended to go through the corresponding tutorials before proceeding.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/SyntaxandStyleGroup(["`Syntax and Style`"]) cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/FunctionsGroup(["`Functions`"]) cpp/SyntaxandStyleGroup -.-> cpp/comments("`Comments`") cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/operators("`Operators`") cpp/ControlFlowGroup -.-> cpp/conditions("`Conditions`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/FunctionsGroup -.-> cpp/function_parameters("`Function Parameters`") subgraph Lab Skills cpp/comments -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} cpp/variables -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} cpp/data_types -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} cpp/operators -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} cpp/conditions -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} cpp/for_loop -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} cpp/function_parameters -.-> lab-96128{{"`Custom Sort Method for STL Pair Template`"}} end

Create an Empty Vector and Fill it With Elements

We will start by declaring an empty vector of pairs and then filling it with some elements.
In this step, we will create an empty vector.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main() {
  vector<pair<int, int>> v;

  return 0;
}

In this code block, we just included the required header files and declared an empty vector of pairs.

Fill the Vector with Elements

After creating an empty vector, we can add elements to it. We will be adding elements by using the push_back method of the vector class. In this case, we are adding integer pairs to the vector.

int main() {
  vector<pair<int, int>> v;
  v.push_back(make_pair(1, 5));
  v.push_back(make_pair(1, 3));
  v.push_back(make_pair(2, 6));
  v.push_back(make_pair(2, 4));
  v.push_back(make_pair(5, 24));

  return 0;
}

In this code block, we add 5 pairs to the vector v.

Create a Custom Sort Method

To create a custom sort method, we need to first define a comparison function. The comparison function will compare two pairs and return a boolean value indicating whether the first pair is less than the second pair. In this case, we will compare the first element of each pair, and if they are equal, we will compare the second elements of the pairs.

bool cmp(pair<int, int> x, pair<int, int> y)
{
    if (x.first != y.first)
        return x.first < y.first;
    else
        return x.second < y.second;
}

In this code block, we have created a comparison function that takes two pairs of integers as arguments and returns a boolean value based on our specified conditions. The function first compares the first element of each pair. If they are not equal, the function returns the result of the comparison. If they are equal, the function compares the second element of the pair and returns the result of the comparison.

Use sort to Sort the Vector

In this step, we will sort the elements in the vector based on the custom sort method we created in the previous step. To sort the vector, we need to call the sort method of the STL with the vector as its arguments and pass the custom sort method as the third argument.

int main() {
  vector<pair<int, int>> v;
  v.push_back(make_pair(1, 5));
  v.push_back(make_pair(1, 3));
  v.push_back(make_pair(2, 6));
  v.push_back(make_pair(2, 4));
  v.push_back(make_pair(5, 24));


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

  return 0;
}

In this code block, we have sorted the vector v using the sort method of the STL. We have passed the custom sort method cmp as the third parameter.

Print the Sorted Vector

In this step, we will print the sorted vector elements. We will iterate through the vector using a for loop and print the first and second elements of each pair.

int main() {
  // previous code

  for (auto p : v)
  {
      cout << p.first << " " << p.second << endl;
  }
  return 0;
}

In this final code block, we have used a for-each loop to access the pairs in the vector and print them to the console. Now, let's run the code to see the results.

Run the Code

To run the code, you need to compile it using the following command:

g++ ~/project/main.cpp -o main && ./main

After running the code, you will see the sorted pairs printed in ascending order.

Full Code Example

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

bool cmp(pair<int, int> x, pair<int, int> y)
{
    if (x.first != y.first)
        return x.first < y.first;
    else
        return x.second < y.second;
}

int main() {
    vector<pair<int, int>> v;
    v.push_back(make_pair(1, 5));
    v.push_back(make_pair(1, 3));
    v.push_back(make_pair(2, 6));
    v.push_back(make_pair(2, 4));
    v.push_back(make_pair(5, 24));

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

    for (auto p : v)
    {
        cout << p.first << " " << p.second << endl;
    }
    return 0;
}

Summary

In this lab, we learned how to create a custom sort method for a pair template and implement it using a vector in C++. We created an empty vector, added elements to it, created a comparison function, used sort function to sort the elements in the vector using our custom sort method, and printed the sorted vector. The custom sort method can be used to sort the pairs in the vector based on some specific requirements or conditions that we define in the code.

Other C++ Tutorials you may like