I have vector <Class> array, which contain a sequence of class instances, now could I sort the array accoding to the member value of class?
Thanks
Printable View
I have vector <Class> array, which contain a sequence of class instances, now could I sort the array accoding to the member value of class?
Thanks
You need to define your own predicate. Check out this thread.
edited: fixed link
http://www.codeguru.com/forum/showth...hreadid=199819
Jeff
But, how to define my own predicate, could you give a example for following code? thanks:
class Me
{
int m_x;
public:
int GetX()
{
return m_x;
}
void SetX(int x)
{
m_x=x;
}
};
void main()
{
vector<Me> ArrayMe;
for(int i=0; i<10; i++)
{
int x=rand()%10;
Me me;
me.setx(x);
Array.push_back();
}
//here I want ro sort ArrayMe according to m_x value
// how do I do?
}
thanks
First of all, my link was bad. I fixed it.
Second, a better and easier would be to define operator<.
Try this:
Code:#include <vector>
#include <algorithm>
using namespace std;
class Me
{
int m_x;
public:
int GetX() const
{
return m_x;
}
void SetX(int x)
{
m_x=x;
}
bool operator<(const Me& rhs) const
{
return GetX() < rhs.GetX();
}
};
void main()
{
vector<Me> ArrayMe;
for(int i=0; i<10; i++)
{
int x=rand()%10;
Me me;
me.SetX(x);
ArrayMe.push_back(me);
}
std::sort(ArrayMe.begin(), ArrayMe.end());
}
Thanks it is works!