I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.
What Is Compare Predicate?
We know that sorting can be performed by comparing two elements and arranging the elements either in ascending order or in descending order. For any programming API, this will be an easy task when the elements fall under standard data types like integers, floats, etc. Now, when the type is user-defined, say for example; class instance, the API may not know how to sort the elements. Or, even if it does it may not be the way we want it. And, this is where the need for the “Compare Predicate” comes into the picture.
In this article, we will create a Department class and sort the instances of it through a couple of compare predicates. Let us start.
The Department Class: To Explain C++ List Sort
The below code shows the complete department class:
Code snippet 1.1: Members
The department class has three members to store department id, name and number of staff employed by the department. This is shown in the code snippet 1.1
Code snippet 1.2: Department constructor
The constructor takes three parameters and uses those passed-in parameters to initialize all its members. Note that our class does not have any other constructors and there is no default constructor as well. This will make sure initializing all the data members with the valid data during construction itself.
Code Snippet 1.3: Getter Functions
We gave two getter functions which will return the private members m_DeptID and m_NumberOfStaffs.
Code Snippet 1.4: Printing the Department information
The Print_Department() member of the Department class prints the Department data into the console output window. Here, we are using the C++ iosteam to list of out the members along with the concatenated string. That’s all about the Department class and let us explore some of the global function that deals with this department class instances and c++ standard list.
Adding Department Class Instance to C++ List
The global function Add_ListElements takes the C++ Standard List as parameter and adds the department instances into it. Function code is below:
Code Snippet 2.1
Whenever we call the Add_ListElements(), it should add five default departments to the supplied C++ list for demo purposes. Hence, first, we are clearing the list by calling the standard list clear() function.
Code Snippet 2.2
Five department objects are constructed and note that all the instances are kept constant as we are not going to change the instance members and we will perform only sorting on these demo departments.
Code Snippet 2.3
We are storing the departments one by one into the c++ standard list by making use of the push_back() function call.
4. Iterating Department Class Instances in C++ List
The Print_List() is written to iterate through the supplied list and prints information about the department class in the console window. In each iteration, we retrieve the Department class instance and make a call to its member Print_Department() to print the department information Id, Name etc. The function below:
Compare Predicates for Sorting Departments in the List
The Standard list “sort()” function does not know how to sort C++ user-defined types say Structures, Class objects, etc. Through “Compare Predicates”, we can teach the Sort() function when it should perform the swapping.
The Compare Predicate expects two parameters and returns a Boolean. Let us say the parameters are First and Second and the body of the predicate should tell this order is right or wrong. When we say the order is right, we should return true otherwise false. When the predicate returns false, the sort() function of the standard list knows that Second and First should be swapped so that Second goes first in the sorting order.
Recommended for you
Note that the First and Second parameter should match with the data type of the container (In this example it is Department).
5.1 Compare Predicate – Sort By Department ID
Our first predicate function tells how to sort the department by its department id. Have a look at the predicate function below:
In the above code, we are telling how to sort the department id in Ascending Order. When parameter First is lower than parameter Second, we don’t want to swap it, and hence we return true. When the first parameter is higher than the second one, we return false a statement that swapping is required. When both parameters First and Second has same value, we return false stating that no swapping is required. We can even return true, but the swapping has no effect here.
5.2 Compare Predicate – Sort By Number of Staffs
The second predicate is written to perform the sorting in Descending Order. Note that how the operator "<" and ">" is used and how different it performs the previous predicate function which performs sorting in Ascending Order. The code for the second predicate is given below:
OK. Now it is time to create the C++ List, store the Department instances in it and perform sorting through our predicate functions. Let us move ahead!
C++ Compare Predicate in Action
OK. First, let us prepare the List and print it on the console output window. First, we used our global function Add_ListElements() by passing the C++ Standard List as a parameter. The function packs five same Department in the passed-in list. Next, we are supplying Department packed list to the global function Print_List() to print the content of the List. The code is below:
At this stage, we have a C++ Standard List which has five Department object in it. This is shown in below picture:
Next, we are sorting Department objects by its ID. To sort the department by ID, we are passing the Predicate function Compare_IDS_Predicate_Asc to "Sort()" method of the List. Now, sort method knows how to sort the department object. It iterates through the C++ List and makes use of the predicate function Compare_IDS_Predicate_Asc to decide the order between to side-by-side department object in the list. After the call to Sort(), the Departments in the lists are ordered in Ascending by it department IDs, and We print the list to console output window.
The same way by making use of the predicate function Compare_TotEmps_Predicate_Desc, we are calling the sort() method again. This time the list will be sorted by the Number Of Staffs in the department in descending order. The code snippet is below:
The two sort operation is illustrated as shown below:
The complete code Example - C++ List Sort() with Compare Predicates
The output of the program result is shown below:
This article is accurate and true to the best of the author’s knowledge. Content is for informational or entertainment purposes only and does not substitute for personal counsel or professional advice in business, financial, legal, or technical matters.
© 2018 sirama