
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Structure Sorting in C++
A structure in C++ is a user-defined data type, which is used to group and store variables of different data types under a single name.
In this article we will see how to sort an array of structures using conditions on member variables. For this we will be using the sort() function which is defined under <algorithm> header file.
Syntax
Here is the following syntax of sort() function.
sort(start_index, end_index, comparison_function);
start_index is an iterator (or pointer) to the first element of the array of structures.
end_index is an iterator (or pointer) to one past the last element (means last_index + 1).
comparison_function is a user-defined function which compares two structure variables on given condition and returns true or false.
In the following example, we will define a structure called a book and will provide data members to it: name, number of pages, and price. Then further we will sort them based on their price.
Steps for Sorting Structure
Here are the following key steps to follow to write a program to sort an array of structure in C++:
- First, define a comparison function, which will take two structure variables as parameters.
- Inside the function, write a method to compare specific data members, which you want to compare (in this example; price) and return true or false based on order.
- Then this comparison function will be passed as the third argument to the sort() function.
- And then this sort() function will use the logic to arrange the structures accordingly.
Example of Structure Sorting
Here is the following example code taking an array of structure of size five and sorting it based on price using sort() function in C++:
#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; } int main() { book book_arr[5] = { {"C Programming", 260, 450}, {"DBMS Guide", 850, 775}, {"Learn C++", 350, 520}, {"Data Structures", 380, 430}, {"Learn Python", 500, 300} }; sort(book_arr, book_arr + 5, compareBook); for (int i = 0; i < 5; i++) cout << book_arr[i].title << ": " << book_arr[i].pages << ", Rs" << book_arr[i].price << endl; return 0; }
Output
Learn Python: 500, Rs300 Data Structures: 380, Rs430 C Programming: 260, Rs450 Learn C++: 350, Rs520 DBMS Guide: 850, Rs775