How To Sort A Vector With Non Numeric Elements

September 19, 2008

Have you ever faced a problem to sort STL vector with non number elemnts (say structs or other classes)? The problem with sort function is that it should know about the less than (<) operator. So the problem would be solved if you defined a < operator for the element type.

The following example illustrates how to sort a vector with elements of type struct.


#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;

// Here is a simple struct
struct MyStruct
{
   int Num;
   // Define the operator <
   bool operator <(const MyStruct& Rhs)
   {
      return (Num < Rhs.Num);      
   }
};
 
int main()
{  
   vector<MyStruct> MyVector;
   // Let the size be 5.
   MyVector.resize(5);
   // Push 5 instances of MyStruct with Num ranging
   // from 5 to 1
   MyStruct TestStruct;
   int i = 0;
   for (i = 0; i < 5; ++i)
   {
      TestStruct.Num = 5 - i;
      MyVector[i] = TestStruct;
   }
   // Now sort the vector
   sort(MyVector.begin(), MyVector.end());
   // Try to display Num for each element. It is sorted
   for (i = 0; i < 5; ++i)
   {
      cout << MyVector[i].Num << '\n';
   }
   return 0;
}

You can use the same technic for any vector with non number elements. The only condition is that you should have a < operator defined for the element data type.