# How do you sort a list and then subsort it by something else?*solved*

This topic is 5070 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a list of structs. The struct has an operator to sort by:
struct LOADEDTEXTURE
{
IDirect3DTexture9 *m_texture;     //the texture
string m_sFilename;               //the filename of the texture
int m_nWidth;                     //width of the texture
int m_nHeight;                    //height of the texture
int m_nArea;                      //area of texture
list <TILE> m_TileList;           //List of tiles within a texture
{
return a->m_nWidth > b->m_nWidth;
}
};


Then I just go sort:
//sort m_lstMergeList, largest area first, smallest last


And that works. Basically the structs with the greatest width appear in the front of the list. Now, I want to subsort, so that structs with the same width are sorted by height (so greater height is first). So how do I do this? Do I need another operator in my struct and how do I use it? [Edited by - utilae on March 3, 2005 2:36:45 AM]

##### Share on other sites
Two ways to do it: Either define an ordering for the sort function which uses the height to break ties, or sort by height first and then do a "stable sort" by width.

##### Share on other sites
I was thinking of sorting by height, then by width, but I don't know how to use operators as well as use them with sort. Could someone give me some example code.

##### Share on other sites
Quote:
 Original post by utilaeI was thinking of sorting by height, then by width

I know you were. But if you're using multiple sorts to accomplish a sub-sorting, then you sort by the primary discriminator last.

Quote:
 but I don't know how to use operators as well as use them with sort.
I find that difficult to believe, given that you just used one in your code. (You used it in a very bizarre way, but still.)

##### Share on other sites
Got it from an example I found on sorting lists.

##### Share on other sites
Quote:
 Original post by SneftelTwo ways to do it: Either define an ordering for the sort function which uses the height to break ties, or sort by height first and then do a "stable sort" by width.
You just took the words right out of my mouth didn't you?!
Here's what we mean:
    //opertor to sort loadedtexture struct    const bool operator()(const LOADEDTEXTURE *a,const LOADEDTEXTURE *b) const    {        if (a->m_nWidth > b->m_nWidth) return true;        if (a->m_nWidth == b->m_nWidth) return a->m_nHeight > b->m_nHeight;        return false;    }};

##### Share on other sites
Ok, sweet as iMalc, thanks that works.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 10
• 11
• 13
• 9
• 11
• ### Forum Statistics

• Total Topics
634088
• Total Posts
3015449
×