|
-
July 18th, 2002, 02:20 PM
#1
Stl sorting question....
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
-
July 18th, 2002, 02:27 PM
#2
You need to define your own predicate. Check out this thread.
edited: fixed link
http://www.codeguru.com/forum/showth...hreadid=199819
Jeff
Last edited by jfaust; July 18th, 2002 at 02:55 PM.
-
July 18th, 2002, 02:44 PM
#3
Thanks, but How to define ...
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
-
July 18th, 2002, 03:00 PM
#4
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());
}
-
July 18th, 2002, 03:09 PM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|