------------------------------------------------------------------------------
MC logo
STL Sorting Vectors
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[STL Vector 101] [STL Sorting Vectors] [stlist_cpp] [STL Map 1] [STL Map 2] [Word Counter]
stvec.cpp
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/* Sort comparison to get an descending sort. */
bool descend(int x, int y) { return y < x; }

/* Comparison where odds come first and ascend, evens come last and
   descend. */
bool evenodd(int x, int y)
{
        if(x&1) {
                // First number is odd.
                if(y&1)
                        // So is the second.  Just use their normal order.
                        return x < y;
                else
                        // First odd, second even, so first is always first.
                        return true;
        } else {
                // First number even.
                if(y&1)
                        // Second odd.  Second should go first.
                        return false;
                else
                        // Both even.  Use reverse order to get descending.
                        return y < x;
        }
}

/*
 * Print the vector.
 */
void print(vector<int> &vec)
{
        vector<int>::iterator i;
        for(i = vec.begin(); i != vec.end(); ++i) {
                cout << *i << " ";
        }
        cout << endl;
}

/*
 * Simple STL vector list demo.
 */
main()
{
        vector<int> vec;

        // Read some integers into the vector.
        int in;
        while(cin >> in) {
                vec.push_back(in);
        }

        cout << "----------------------------------------"
             << "----------------------------------------" << endl;

        // Print them.
        print(vec);

        // Print them backwards.
        vector<int>::iterator i = vec.end();
        while(i != vec.begin())
                cout << *--i << " ";
        cout << endl;
        
        // Sort them ascending, and print.
        sort(vec.begin(), vec.end());
        print(vec);
        
        // Sort them descending, and print.
        sort(vec.begin(), vec.end(), descend);
        print(vec);

        // Sort them so that odd ones come last, and print.
        sort(vec.begin(), vec.end(), evenodd);
        print(vec);
}

The sort method is provided by the standard libraries. If you recall, it can sort arrays taking pointers. It can sort STL containers taking iterators.