File: stablesort.cc

package info (click to toggle)
c%2B%2B-annotations 12.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 13,044 kB
  • sloc: cpp: 24,337; makefile: 1,517; ansic: 165; sh: 121; perl: 90
file content (73 lines) | stat: -rw-r--r-- 2,344 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
71
72
73
    #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
                Pss("Hampson",   "Godalming"),
                Pss("Moran",     "Eugene"),
                Pss("Goldberg",  "Eugene"),
                Pss("Moran",     "Godalming"),
                Pss("Goldberg",  "Chicago"),
                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
    */