GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: Add Line Numbers


A Paste by Anonymous
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template< class _T >
void displayvect( vector<_T>& v ) {
    for( unsigned x = 0; x < v.size(); ++x )
        cout << v[x] << \" \" << endl;
    cout << endl;
}

enum SortMode { INT, DOUBLE };

class sorttest {
    int x;
    double y;
    static SortMode sm;
public:
    sorttest( int i, double f ) : x(i), y(f) {}
    bool operator<( sorttest& t ) {
        switch( sm ) {
        case INT: return x < t.x;
        case DOUBLE: return y < t.y;
        }
        return false;
    }
    static void setSort( SortMode s ) { sm = s; }

    friend ostream& operator<<( ostream& os, sorttest& st );
};

// initalize static member
SortMode sorttest::sm( INT );

ostream& operator<<( ostream& os, sorttest& st ) {
    os << \"(\" << st.x << \", \" << st.y << \")\";
    return os;
}

int main() {
    vector<sorttest> testv;
    testv.push_back( sorttest( 9, 8.5 ) );
    testv.push_back( sorttest( 4, 6.3 ) );
    testv.push_back( sorttest( 5, 4.8 ) );
    testv.push_back( sorttest( 0, 7.9 ) );
    testv.push_back( sorttest( 3, 3.7 ) );

    displayvect( testv );

    // sort on int field (starts with int by default )
    sort( testv.begin(), testv.end() );
    displayvect( testv );

    // switch sort mode for class
    sorttest::setSort( DOUBLE );

    sort( testv.begin(), testv.end() );
    displayvect( testv );
    
    return 0;
}