Structure Sorting in C++


Here we will see how to sort using some condition on some member variables of the structure in C++. In this example we will take a structure called book. The book will hold name, number of pages, and price. We will sort them based in the price.

For comparing two structures, we have to define a function. This function will compare them with these parameters. This comparison function is used inside the sort function to sort the values.

Example

#include <iostream>
#include<algorithm>
using namespace std;
struct book {
   string title;
   int pages;
   float price;
};
bool compareBook(book b1, book b2) {
   if(b1.price < b2.price) {
      return true;
   } return false;
}
main() {
   book book_arr[5];
   book_arr[0].title = "C Programming";
   book_arr[0].pages = 260;
   book_arr[0].price = 450;
   book_arr[1].title = "DBMS Guide";
   book_arr[1].pages = 850;
   book_arr[1].price = 775;
   book_arr[2].title = "Learn C++";
   book_arr[2].pages = 350;
   book_arr[2].price = 520;
   book_arr[3].title = "Data Structures";
   book_arr[3].pages = 380;
   book_arr[3].price = 430;
   book_arr[4].title = "Learn Python";
   book_arr[4].pages = 500;
   book_arr[4].price = 300;
   sort(book_arr, book_arr + 5, compareBook);
   for(int i = 0; i<5; i++) {
      cout << book_arr[i].title << "\t\t" << book_arr[i].pages << "\t\t" <<
         book_arr[i].price << endl;
   }
}

Output

Learn Python 500 300
Data Structures 380 430
C Programming 260 450
Learn C++ 350 520
DBMS Guide 850 775

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements