]> git.lyx.org Git - lyx.git/blob - src/support/lyxalgo.h
Create a new support function lyx::count to use in place of std::count.
[lyx.git] / src / support / lyxalgo.h
1 // -*- C++ -*-
2
3 #ifndef LYX_ALGO_H
4 #define LYX_ALGO_H
5
6 #include <utility>
7 #include <iterator>
8
9 namespace lyx {
10
11
12 /// Returns true if the sequence first,last is sorted, false if not.
13 template <class For>
14 bool sorted(For first, For last)
15 {
16         if (first == last) return true;
17         For tmp = first;
18         while (++tmp != last) {
19                 if (*tmp < *first++) return false;
20         }
21         return true;
22 }
23
24
25 /// Cmp is the same Cmp as you would pass to std::sort.
26 template <class For, class Cmp>
27 bool sorted(For first, For last, Cmp cmp)
28 {
29         if (first == last) return true;
30         For tmp = first;
31         while (++tmp != last) {
32                 if (cmp(*tmp, *first++)) return false;
33         }
34         return true;
35 }
36
37
38 struct firster {
39         template <class P1, class P2>
40         P1 operator()(std::pair<P1, P2> const & p) {
41                 return p.first;
42         }
43 };
44
45
46 template <class InputIter, class OutputIter, class Func>
47 OutputIter copy_if(InputIter first, InputIter last,
48                OutputIter result, Func func) 
49 {
50         for (; first != last; ++first) {
51                 if (func(*first)) {
52                         *result++ = *first;
53                 }
54         }
55         return result;
56 }
57
58
59 /// A slot in replacement for std::count for systems where it is broken.
60 template <class Iterator, class T>
61 typename std::iterator_traits<Iterator>::difference_type
62 count (Iterator first, Iterator last, T const & value)
63 {
64 #ifdef HAVE_STD_COUNT
65         return std::count(first, last, value);
66 #else
67         std::iterator_traits<Iterator>::difference_type n = 0;
68         while (first != last) 
69                 if (*first++ == value) ++n;
70         return n;
71 #endif
72 }
73
74 } // namespace lyx
75
76 #endif