This C++ program demonstrates the stable_sort() algorithm. The program creates vector of objects of class Student which has attributes – name, section and group. The stable_sort algorithm first sorts the elements with name as the key and then the elements are sorted with their section as the key. The order of the elements with same keys is maintained.
Here is the source code of the C++ program which demonstrates the stable_sort() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Demonstrate the stable_sort() Algorithm
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
struct Student {
std::string name;
int sec;
char group;
};
bool compBySec(Student a, Student b)
{
return a.sec < b.sec;
}
bool compByGroup(Student a, Student b)
{
return a.group < b.group;
}
bool compByName(Student a, Student b)
{
return a.name < b.name;
}
void print(const std::vector <Student>& v)
{
std::cout << "Name \tSec\tGroup" << std::endl;
for (unsigned int i = 0; i < v.size(); i++)
{
std::cout << v[i].name << "\t" << v[i].sec<< "\t"
<< v[i].group << std::endl;
}
}
int main()
{
std::vector <Student> Students;
std::string name[] = {"Andrew", "Battle", "Chen ", "Fox ",
"Furia ", "Gazsi ", "Kanaga", "Rohde "};
int sec[] = {3, 4, 3, 3, 1, 4, 3, 2};
int group[] = {'A', 'C', 'A', 'A', 'A', 'B', 'B', 'A'};
for (int i = 0; i < 8; i++)
{
Student p;
p.name = name[i];
p.sec = sec[i];
p.group = group[i];
Students.push_back(p);
}
std::stable_sort(Students.begin(), Students.end(), compByName);
std::cout << "Stable Sort by name" << std::endl;
print(Students);
std::cout << std::endl;
std::stable_sort(Students.begin(), Students.end(), compBySec);
std::cout << "Stable Sort by section" << std::endl;
print(Students);
}
$ a.out Stable Sort by name Name Sec Group Andrew 3 A Battle 4 C Chen 3 A Fox 3 A Furia 1 A Gazsi 4 B Kanaga 3 B Rohde 2 A Stable Sort by section Name Sec Group Furia 1 A Rohde 2 A Andrew 3 A Chen 3 A Fox 3 A Kanaga 3 B Battle 4 C Gazsi 4 B
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Apply for Computer Science Internship
- Apply for C++ Internship
- Practice Computer Science MCQs
- Check Computer Science Books
- Check Programming Books