vector - rbegin and rend

////////////////////////////////////////
//      2018/04/18 7:36:56
//      vector - rbegin and rend

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

class ID
{
private:
    string name;
    int score;
public:
    friend bool operator < (const ID&, const ID&);
    ID(string name, int score) :name(name), score(score){}

    void display(){
        cout.setf(ios::left);
        cout << setw(3) << score << name << endl;
    }
};
//----------------------------------------------
//comperation function for sorting
bool operator <(const ID& a, const ID& b){
    return a.score < b.score;
}

typedef vector<ID> Vector;

int main(){
    Vector v;
    Vector::iterator iter;
    v.push_back(ID("Smith A.",96));
    v.push_back(ID("Amstrong B.",91));
    v.push_back(ID("Waston D.",82));

    for (iter = v.begin(); iter != v.end(); iter++){
        iter->display();
    }

    sort(v.begin(), v.end()); // sort algorithm
    cout << endl << "Sorted by Score" << endl;
    cout << "====================" << endl;
    for (iter = v.begin(); iter != v.end(); iter++){
        iter->display();
    }

    cout << endl << "Reverse output" << endl;
    cout << "=================" << endl;
    Vector::reverse_iterator r = v.rbegin();
    while (r != v.rend()){
        r->display();
        r++;
    }
    cout << endl;

    return 0;
}

/*
OUTPUT:
    96 Smith A.
    91 Amstrong B.
    82 Waston D.

    Sorted by Score
    ====================
    82 Waston D.
    91 Amstrong B.
    96 Smith A.

    Reverse output
    =================
    96 Smith A.
    91 Amstrong B.
    82 Waston D.
*/ 
posted @ 2018-04-18 12:30  老耗子  阅读(95)  评论(0编辑  收藏  举报