File: stablesort.cc

package info (click to toggle)
c%2B%2B-annotations 8.2.0-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 11,804 kB
  • ctags: 2,845
  • sloc: cpp: 15,418; makefile: 2,473; ansic: 165; perl: 90; sh: 29
file content (70 lines) | stat: -rw-r--r-- 2,280 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    #include <algorithm>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <iterator>
    using namespace std;

    struct Pss: public pair<string, string>                             // 1
    {
        Pss(string const &s1, string const &s2)
        :
            pair<string, string>(s1, s2)
        {}
    };
    ostream &operator<<(ostream &out, Pss const &p)           // 2
    {
        return out << "    " << p.first << " " << p.second << '\n';
    }
    class Sortby
    {
        string Pss::*d_field;
        public:
            Sortby(string Pss::*field)                             // 3
            :
                d_field(field)
            {}
            bool operator()(Pss const &p1, Pss const &p2) const         // 4
            {
                return p1.*d_field < p2.*d_field;
            }
    };
    int main()
    {
        vector<Pss> namecity;                                           // 5

        namecity.push_back(Pss("Hampson",   "Godalming"));
        namecity.push_back(Pss("Moran",     "Eugene"));
        namecity.push_back(Pss("Goldberg",  "Eugene"));
        namecity.push_back(Pss("Moran",     "Godalming"));
        namecity.push_back(Pss("Goldberg",  "Chicago"));
        namecity.push_back(Pss("Hampson",   "Eugene"));

        sort(namecity.begin(), namecity.end(), Sortby(&Pss::first));    // 6

        cout << "sorted by names:\n";
        copy(namecity.begin(), namecity.end(), ostream_iterator<Pss>(cout));

                                                                        // 7
        stable_sort(namecity.begin(), namecity.end(), Sortby(&Pss::second));

        cout << "sorted by names within sorted cities:\n";
        copy(namecity.begin(), namecity.end(), ostream_iterator<Pss>(cout));
    }
    /*
        Displays:
            sorted by names:
                Goldberg Eugene
                Goldberg Chicago
                Hampson Godalming
                Hampson Eugene
                Moran Eugene
                Moran Godalming
            sorted by names within sorted cities:
                Goldberg Chicago
                Goldberg Eugene
                Hampson Eugene
                Moran Eugene
                Hampson Godalming
                Moran Godalming
    */