Thread: Sorting an array of structures with sort()

  1. #1
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    Sorting an array of structures with sort()

    I want to sort an array of structures based on one of their members. I did this using a sort I wrote, and it works, but I recently discovered that sort() from the standard is about 200 times faster. So I want to sort my stuff with std::sort but I don't know how to use std::sort with an array of structures, sorting based only on a certain member from the structure. I don't even know if it's possible to do this.

    Any help would be appreciated, thanks

    the code from my slow-slow-slow sort function, if it's of any use to give you the idea:

    Code:
    int minVal = 0;
    int minPos;
    NPC tmp;
    
    for (int u = 0; u < MainMap.numNPCs-1; ++u) {
    	minPos = -1;
    	for (int v = u; v < MainMap.numNPCs; ++v) {
    		if (NPCs[v].aPixY < minVal || minPos == -1) {
    			minVal = NPCs[v].aPixY;
    			minPos = v;
    		}
    	}
    	tmp = NPCs[u];
    	NPCs[u] = NPCs[minPos];
    	NPCs[minPos] = tmp;
    }

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Maybe your sort() is so much slower than std::sort() because you're sorting structures and not numbers or characters.

    Just a thought.

  3. #3
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    I could be wrong about this but I think if you overload the relational operators (==,>,<,>=,<=) you can use sort. As long as the computer understands what "if (myclass1>myclass2)" means along with the other operators I think sort will work.

    If not, let us know and we can help you with creating your own sort which there are plenty of and that will be more efficient than the one you have now.

  4. #4
    Registered User rmullen3's Avatar
    Join Date
    Nov 2001
    Posts
    330

    _

    Overloading the boolean operators seems to have done it... thanks PJYelton...

    EDIT: yeah, it works. Thanks fellows!
    Last edited by rmullen3; 01-03-2003 at 03:10 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array of structures help!
    By voodoo3182 in forum C Programming
    Replies: 12
    Last Post: 08-03-2005, 02:58 PM
  2. Sorting
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 11-10-2003, 05:21 PM
  3. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  4. passing array of structures to function
    By bvnorth in forum C Programming
    Replies: 3
    Last Post: 08-22-2003, 07:15 AM
  5. Array sorting problems
    By cazil in forum C++ Programming
    Replies: 2
    Last Post: 02-04-2002, 01:36 PM