]> git.lyx.org Git - lyx.git/blob - src/support/lyxalgo.h
another safety belt
[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 namespace lyx {
22
23
24 /// Returns true if the sequence first,last is sorted, false if not.
25 template <class For>
26 bool sorted(For first, For last)
27 {
28         if (first == last) return true;
29         For tmp = first;
30         while (++tmp != last) {
31                 if (*tmp < *first++) return false;
32         }
33         return true;
34 }
35
36
37 /// Cmp is the same Cmp as you would pass to std::sort.
38 template <class For, class Cmp>
39 bool sorted(For first, For last, Cmp cmp)
40 {
41         if (first == last) return true;
42         For tmp = first;
43         while (++tmp != last) {
44                 if (cmp(*tmp, *first++)) return false;
45         }
46         return true;
47 }
48
49
50 struct firster {
51         template <class P1, class P2>
52         P1 operator()(std::pair<P1, P2> const & p) {
53                 return p.first;
54         }
55 };
56
57
58 /**
59  * copy elements in the given range to the output iterator
60  * if the predicate evaluates as true
61  */
62 template <class InputIter, class OutputIter, class Func>
63 OutputIter copy_if(InputIter first, InputIter last,
64                OutputIter result, Func func)
65 {
66         for (; first != last; ++first) {
67                 if (func(*first)) {
68                         *result++ = *first;
69                 }
70         }
71         return result;
72 }
73
74
75 /// A slot in replacement for std::count for systems where it is broken.
76 template <class Iterator, class T>
77 typename std::iterator_traits<Iterator>::difference_type
78 count (Iterator first, Iterator last, T const & value)
79 {
80 #ifdef HAVE_STD_COUNT
81         return std::count(first, last, value);
82 #else
83         std::iterator_traits<Iterator>::difference_type n = 0;
84         while (first != last)
85                 if (*first++ == value) ++n;
86         return n;
87 #endif
88 }
89
90 /// Remove all duplicate entries in c.
91 template<class C>
92 void eliminate_duplicates(C & c)
93 {
94         std::sort(c.begin(), c.end());
95         typename C::iterator p = std::unique(c.begin(), c.end());
96         c.erase(p, c.end());
97 }
98
99 } // namespace lyx
100
101 #endif // LYX_ALGO_H