How To Sort A Vector With Non Numeric Elements

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.

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 MyVector;
   // Let the size be 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; } [/sourcecode] 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.


One Response to How To Sort A Vector With Non Numeric Elements

  1. wuyongjian says:

    Good! Thanks 🙂

    Will redirect on my blog, is it ok? ^.^

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: