]> git.lyx.org Git - lyx.git/blob - src/support/lyxalgo.h
prepare Qt 5.6 builds
[lyx.git] / src / support / lyxalgo.h
1 // -*- C++ -*-
2 /**
3  * \file lyxalgo.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  * A variety of useful templates.
12  */
13
14 #ifndef LYX_ALGO_H
15 #define LYX_ALGO_H
16
17 #include <utility>
18 #include <iterator>
19 #include <algorithm>
20
21
22 namespace lyx {
23
24
25 /// Returns true if the sequence first,last is sorted, false if not.
26 template <class For>
27 bool sorted(For first, For last)
28 {
29         if (first == last) return true;
30         For tmp = first;
31         while (++tmp != last) {
32                 if (*tmp < *first++) return false;
33         }
34         return true;
35 }
36
37
38 /// Cmp is the same Cmp as you would pass to std::sort.
39 template <class For, class Cmp>
40 bool sorted(For first, For last, Cmp cmp)
41 {
42         if (first == last) return true;
43         For tmp = first;
44         while (++tmp != last) {
45                 if (cmp(*tmp, *first++)) return false;
46         }
47         return true;
48 }
49
50
51 struct firster {
52         template <class P1, class P2>
53         P1 operator()(std::pair<P1, P2> const & p) {
54                 return p.first;
55         }
56 };
57
58
59 /**
60  * copy elements in the given range to the output iterator
61  * if the predicate evaluates as true
62  */
63 template <class InputIter, class OutputIter, class Func>
64 OutputIter copy_if(InputIter first, InputIter last,
65                OutputIter result, Func func)
66 {
67         for (; first != last; ++first) {
68                 if (func(*first)) {
69                         *result++ = *first;
70                 }
71         }
72         return result;
73 }
74
75
76 /// Remove all duplicate entries in c.
77 template<class C>
78 void eliminate_duplicates(C & c)
79 {
80         // It is a requirement that the container is sorted for
81         // std::unique to work properly.
82         std::sort(c.begin(), c.end());
83         c.erase(std::unique(c.begin(), c.end()), c.end());
84 }
85
86
87 #ifdef LYX_USE_CXX11
88 using std::next;
89 #else
90 /// Replacement of std::next for older compilers
91 template <typename It, typename Diff>
92 inline It next(It i, Diff n = 1)
93 {
94         std::advance(i, n);
95         return i;
96 }
97 #endif
98
99
100 #ifdef LYX_USE_CXX11
101 using std::prev;
102 #else
103 /// Replacement of std::prev for older compilers
104 template <typename It, typename Diff>
105 inline It prev(It i, Diff n = 1)
106 {
107         std::advance(i, -n);
108         return i;
109 }
110 #endif
111
112 } // namespace lyx
113
114 #endif // LYX_ALGO_H