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
#include
#include

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.
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;
}
[/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.

This entry was posted on Friday, September 19th, 2008 at 1:01 am and is filed under C++, VC++ 2005. You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

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

Good! Thanks 🙂

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