CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jul 2002
    Posts
    79

    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

  2. #2
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    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.

  3. #3
    Join Date
    Jul 2002
    Posts
    79

    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

  4. #4
    Join Date
    Mar 2002
    Location
    California
    Posts
    1,582
    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());
    }

  5. #5
    Join Date
    Jul 2002
    Posts
    79

    Thanks it is works!

    Thanks it is works!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured