Sorting vectors of structs

I am having a hard time wrapping my head around sorting a vector of structs.

Basically I have this struct, STUDENT, with members first name, last name, and class ranking. I have created a vector of object stud of type STUDENT. What I want to do is to sort the vector elements, by the class ranking and display them.


Basically my problem is vectors do not work like arrays. I have to push_back or pop_back in order to operate on elements, and I can't think of a way to do any of the four types of sorting: bubble sort, selection sort, and insertion sort.

Any suggestions? is there a predefined function that does what I want to do?
Last edited on
Yes there is:
http://cplusplus.com/reference/algorithm/sort/

Make your struct like this:
1
2
3
4
5
6
7
struct STUDENT {
  std::string firstname;
  std::string lastname;
  int classRanking

  bool operator() (STUDENT i,STUDENT j) { return (i.classRanking<j.classRanking);}
} student;

The operator function is used by the sort algorithm. Now I will assume that you have a populated vector declared like this:
std::vector<STUDENT> vStudents;
So now you can sort it like this:
std::sort(vStudents.begin(), vStudents.end(), student);

P.S. you need:
1
2
#include <algorithm>
#include <vector> 
Last edited on
You can use standard algorithm std::sort declared in header file algorithm. For example

1
2
3
std::sort( stud.begin(), stud.end(),
              []( const STUDENT &left, const STUDENT &right )
                 { return ( left.classRanking < right.classRanking ); } );
Topic archived. No new replies allowed.