
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Adaptive Merging and Sorting in Data Structure
- Sorting in C++
- Alternative Sorting in C++
- Pancake Sorting in C++
- Sorting Arrays in Perl
- Relative sorting in JavaScript
- Topological Sorting
- Sorting a Strings in Java
- Sorting a vector in C++
- Sorting a String in C#
- Multiple column sorting in MySQL?
- Perform custom sorting in MySQL
- What is Sorting?
- Sorting varchar field numerically in MySQL?
- Sorting a JSON object in JavaScript

Advertisements