1// Example of sorting a struct using a case-insensitive string key.
2//
3// Copyright Steven Ross 2009-2014.
4//
5// Distributed under the Boost Software License, Version 1.0.
6// (See accompanying file LICENSE_1_0.txt or copy at
7// http://www.boost.org/LICENSE_1_0.txt)
8
9// See http://www.boost.org/libs/sort for library home page.
10
11#include <boost/algorithm/string.hpp>
12#include <boost/sort/spreadsort/string_sort.hpp>
13#include <time.h>
14#include <stdio.h>
15#include <stdlib.h>
16#include <algorithm>
17#include <vector>
18#include <iostream>
19#include <fstream>
20#include <string>
21using std::string;
22using namespace boost::sort::spreadsort;
23
24struct DATA_TYPE {
25 string a;
26};
27
28struct lessthan {
29 inline bool operator()(const DATA_TYPE &x, const DATA_TYPE &y) const {
30 return boost::algorithm::ilexicographical_compare(Arg1: x.a, Arg2: y.a);
31 }
32};
33
34struct bracket {
35 inline unsigned char operator()(const DATA_TYPE &x, size_t offset) const {
36 return toupper(c: x.a[offset]);
37 }
38};
39
40struct getsize {
41 inline size_t operator()(const DATA_TYPE &x) const{ return x.a.size(); }
42};
43
44//Pass in an argument to test std::sort
45int main(int argc, const char ** argv) {
46 std::ifstream indata;
47 std::ofstream outfile;
48 bool stdSort = false;
49 unsigned loopCount = 1;
50 for (int u = 1; u < argc; ++u) {
51 if (std::string(argv[u]) == "-std")
52 stdSort = true;
53 else
54 loopCount = atoi(nptr: argv[u]);
55 }
56 double total = 0.0;
57 //Run multiple loops, if requested
58 std::vector<DATA_TYPE> array;
59 for (unsigned u = 0; u < loopCount; ++u) {
60 indata.open(s: "input.txt", mode: std::ios_base::in | std::ios_base::binary);
61 if (indata.bad()) {
62 printf(format: "input.txt could not be opened\n");
63 return 1;
64 }
65 DATA_TYPE inval;
66 indata >> inval.a;
67 while (!indata.eof() ) {
68 array.push_back(x: inval);
69 indata >> inval.a;
70 }
71
72 indata.close();
73 clock_t start, end;
74 double elapsed;
75 start = clock();
76 if (stdSort)
77 std::sort(first: array.begin(), last: array.end(), comp: lessthan());
78 else
79 string_sort(first: array.begin(), last: array.end(), get_character: bracket(), length: getsize(), comp: lessthan());
80 end = clock();
81 elapsed = static_cast<double>(end - start);
82 if (stdSort)
83 outfile.open(s: "standard_sort_out.txt", mode: std::ios_base::out |
84 std::ios_base::binary | std::ios_base::trunc);
85 else
86 outfile.open(s: "boost_sort_out.txt", mode: std::ios_base::out |
87 std::ios_base::binary | std::ios_base::trunc);
88 if (outfile.good()) {
89 for (unsigned u = 0; u < array.size(); ++u)
90 outfile << array[u].a << "\n";
91 outfile.close();
92 }
93 total += elapsed;
94 array.clear();
95 }
96 if (stdSort)
97 printf(format: "std::sort elapsed time %f\n", total / CLOCKS_PER_SEC);
98 else
99 printf(format: "spreadsort elapsed time %f\n", total / CLOCKS_PER_SEC);
100 return 0;
101}
102

source code of boost/libs/sort/example/caseinsensitive.cpp