C++ std::sort with std::array














































C++ std::sort with std::array



 This article is about the sort() algorithm function with std::array container. It is an
 STL algorithm in <algorithm> header file. It rearranges the elements in the comntainer 
 so they are in the ascending order. Same valued elements are not guranteed to maintain
 their order. So there is an another function stable_sort.

sort() can take two forms:
(1) template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); (2) template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
 
 Here the range used is [first, last). The first positioned element is included whereas the 
 last positioned element is not used. Elelments are compared and then swapped according to 
 the following rule: 

two elements are compared equal using operator '<' in definition (1) or by using a comp function in definition (2).

 "comp" is a binary function that accepts two elements in the range as arguments, and 
 returns a value convertible to bool. If one element is smaller it is brought to the front 
 and the greater element is shifted to the back. This function shall not modify any of its
 arguments. comp can either be a function pointer or a function object.

 Here the second definition is discussed. 
 
 Program:
 Enter the name of students along with their marks of subject 1 & 2. Sort the names of
 the students in ascending order of their total marks obtained.

#include<iostream>
#include<algorithm> // for sort function

using namespace std;
// structure of the student object
struct student
{
char name[30];
int sub1;
int sub2;
int total;
};

//compare function which compares between the total marks of 2 students
bool comp(student stu1, student stu2)
{
return (stu1.total < stu2.total);
}

int main()
{
int num, i;
cout<<"Enter the number of students: ";
cin>>num;

student stu[num];

cout<<"Enter the Student Details: \n";
for(i = 0; i < num; i++)
{
cout<<"Name: ";
cin>>stu[i].name;
cout<<"1st and 2nd subject marks: ";
cin>>stu[i].sub1>>stu[i].sub2;
stu[i].total = stu[i].sub1 + stu[i].sub2;
}

// sorting done
sort(stu, stu+num, comp);

cout<<"Students sorted by their total marks in ascending order: "<<endl;
// displaying sorted students
for(i=0;i<num;i++)
cout<<stu[i].name<<endl;
}

Comments