Thread: STL list::sort() sorting structs

  1. #1
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817

    STL list::sort() sorting structs

    I've got some code as follows:
    Code:
    struct Sector
    {
        string strName;
        long lPosition;
    }
    
    list<Sector> lstSector;
    I want to be able to use the list::sort() member function to sort the list by the strName member but I don't know enough about STL to do this. If I create a list<string> linked-list I can simply call the list::sort function without parameters and it will know how to sort by using the string comparison operators. However, since I'm using a struct in the linked-list I think I need to create a predicate or something to pass as a parameter. Anyone experienced enough with this to help me out?

    Also, I am intrigued by everything in the STL that I may be missing out on. I'm thinking of buying a C++ Standard Library book by Nicolai Josuttis(?). Does anyone have this book and can they tell me if its good?
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,490
    i asked a similar question a week or two ago. i think you need to overload the '<' and '>' operators, so that any comparison between the two is really comparing the strings. nope, i haven't read the book.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    I've finally figured it out, I had to make some significant modifications to the struct I had declared to provide it with some boolean operators (>,<,==,etc) and also add in some constructors for the struct. I also changed the way I was calling the list:: push_back function. Then it was a simple matter to call the default list::sort member function with no arguments. Here is some code.

    My new struct:
    Code:
    struct Sector
    {
        string strName;			// TSV Sector Name
        long lPosition;			// Address in input file
        Sector(const Sector& elem) : strName(elem.strName),
    			 lPosition(elem.lPosition)
        {
        };
        Sector(const string& name, const long position) : strName(name),
    				            lPosition(position)
        {
        };
        Sector& operator= (const Sector& elem)
        {
            strName = elem.strName;
            lPosition = elem.lPosition;
        };
        bool operator< (const Sector& elem) const
        {
            return strName < elem.strName;
        };
        bool operator> (const Sector& elem) const
        {
            return strName > elem.strName;
        };
        bool operator== (const Sector& elem) const
        {
            return strName == elem.strName;
        };
    };
    
    list<Sector> lstSectors;		// Linked-list of "Sector" objects
    And the code that adds the stuff to the list:
    Code:
        int iCount = 0;
        string strTemp;
        long lPosition;
        ifstream input("TsvData.Dat");
    	
        // Read through the input file and insert data into the struct/list. ////
    
        input >> strTemp;
        while( !input.eof() )
        {
            // Is this a TSV Sector/SubSector. //////////////////////////////////
    
            if( strTemp[0] == '.' )
            {
                // Initialize file position from start of "strTemp". /////////////
    
                lPosition = input.tellg() - (long) strTemp.length();
    
                // Add "Sector" to linked list and increment count. ///////////////
    
                lstSectors.push_back( Sector(strTemp,lPosition) );
                iCount++;
            }
    
            // Output a dot '.' every 100 records. //////////////////////////////
    
            if( iCount % 100 == 0 )
            {
                cerr << '.';
                cerr.flush();
            }
    
            // Get the next line of data from the file and continue with the loop.
    
            input >> strTemp;
    
        }   // End of "while" loop.
    The above loads the list and will be unsorted in terms of the strName data member. The code to sort the linked-list of structs by the strName member is now simply this:
    Code:
        lstSectors.sort();
    Lastly a snippet of data from a file where I dumped the sorted info to show that it was indeed sorted by the string member and not the order that the data was read in:
    Code:
    Name: .ZSE4201M1 Position: 10680
    Name: .ZSE4202M1 Position: 10379
    Name: .ZSE4601M1 Position: 9998
    Name: .ZSE4701M1 Position: 9495
    Name: .ZSE4801M1 Position: 9276
    Name: .ZSE9001M1 Position: 8465
    Name: .ZSEEU01M1 Position: 6588
    Name: .ZSEMF01M1 Position: 7160
    Name: .ZSEMW01M1 Position: 7528
    Name: .ZSENU01M1 Position: 5340
    Name: .ZSENU01M2 Position: 5960
    Name: .ZSEPD01M1 Position: 0
    Name: .ZSEPD01M2 Position: 688
    Name: .ZSEPD01M3 Position: 1370
    ygfperson, maybe this can help you if you haven't figured out the answer to that question you asked last week.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting an Array of Structs not working
    By ashcan1979 in forum C++ Programming
    Replies: 9
    Last Post: 09-28-2006, 03:07 PM
  2. Can I use STL qsort() for sorting structure?
    By franziss in forum C++ Programming
    Replies: 14
    Last Post: 09-20-2005, 05:34 AM
  3. sorting containers of structs
    By bigSteve in forum C++ Programming
    Replies: 2
    Last Post: 01-06-2004, 02:50 PM
  4. Map Container & Sorting :: STL
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 09-09-2002, 06:01 PM
  5. sorting an array of structs
    By singletrackmind in forum C++ Programming
    Replies: 8
    Last Post: 11-13-2001, 03:33 AM