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,
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.
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<algorithm> // for sort function
using namespace std;
// structure of the student object
//compare function which compares between the total marks of 2 students
bool comp(student stu1, student stu2)
return (stu1.total < stu2.total);
int num, i;
cout<<"Enter the number of students: ";
cout<<"Enter the Student Details: \n";
for(i = 0; i < num; i++)
cout<<"1st and 2nd subject marks: ";
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