]> git.lyx.org Git - lyx.git/blob - src/support/lyxalgo.h
layout as layout
[lyx.git] / src / support / lyxalgo.h
1 // -*- C++ -*-
2 /**
3  * \file lyxalgo.h
4  * Copyright 1995-2002 the LyX Team
5  * Read the file COPYING
6  *
7  * A variety of useful templates.
8  *
9  * \author unknown
10  */
11
12 #ifndef LYX_ALGO_H
13 #define LYX_ALGO_H
14
15 #include <utility>
16 #include <iterator>
17 #include <algorithm>
18
19 namespace lyx {
20
21
22 /// Returns true if the sequence first,last is sorted, false if not.
23 template <class For>
24 bool sorted(For first, For last)
25 {
26         if (first == last) return true;
27         For tmp = first;
28         while (++tmp != last) {
29                 if (*tmp < *first++) return false;
30         }
31         return true;
32 }
33
34
35 /// Cmp is the same Cmp as you would pass to std::sort.
36 template <class For, class Cmp>
37 bool sorted(For first, For last, Cmp cmp)
38 {
39         if (first == last) return true;
40         For tmp = first;
41         while (++tmp != last) {
42                 if (cmp(*tmp, *first++)) return false;
43         }
44         return true;
45 }
46
47
48 struct firster {
49         template <class P1, class P2>
50         P1 operator()(std::pair<P1, P2> const & p) {
51                 return p.first;
52         }
53 };
54
55
56 /**
57  * copy elements in the given range to the output iterator
58  * if the predicate evaluates as true
59  */
60 template <class InputIter, class OutputIter, class Func>
61 OutputIter copy_if(InputIter first, InputIter last,
62                OutputIter result, Func func)
63 {
64         for (; first != last; ++first) {
65                 if (func(*first)) {
66                         *result++ = *first;
67                 }
68         }
69         return result;
70 }
71
72
73 /// A slot in replacement for std::count for systems where it is broken.
74 template <class Iterator, class T>
75 typename std::iterator_traits<Iterator>::difference_type
76 count (Iterator first, Iterator last, T const & value)
77 {
78 #ifdef HAVE_STD_COUNT
79         return std::count(first, last, value);
80 #else
81         std::iterator_traits<Iterator>::difference_type n = 0;
82         while (first != last)
83                 if (*first++ == value) ++n;
84         return n;
85 #endif
86 }
87
88 /// Remove all duplicate entries in c.
89 template<class C>
90 void eliminate_duplicates(C & c)
91 {
92         std::sort(c.begin(), c.end());
93         typename C::iterator p = std::unique(c.begin(), c.end());
94         c.erase(p, c.end());
95 }
96
97 } // namespace lyx
98
99 #endif // LYX_ALGO_H