1 #if !defined HAVE_GREP_H__
2 #define HAVE_GREP_H__
3 // This file is part of the FXT library.
4 // Copyright (C) 2010 Joerg Arndt
5 // License: GNU General Public License version 3 or later,
6 // see the file COPYING.txt in the main directory.
7
8 #include "fxttypes.h"
9
10
11 template <typename Type>
count(const Type * f,ulong n,bool (* func)(Type))12 inline ulong count(const Type *f, ulong n, bool (* func)(Type))
13 // Return number of elements for which func() returns true.
14 {
15 ulong ct = 0;
16 for (ulong k=0; k<n; ++k) if ( func(f[k]) ) ct++;
17 return ct;
18 }
19 // -------------------------
20
21
22 template <typename Type>
grep(const Type * f,ulong n,bool (* func)(Type),Type * g)23 inline ulong grep(const Type *f, ulong n, bool (* func)(Type), Type *g)
24 // Make g[] the sequence of values for which func() returns true.
25 // Return number of 'matching' elements found.
26 {
27 ulong ct = 0;
28 for (ulong k=0; k<n; ++k) if ( func(f[k]) ) g[ct++] = f[k];
29 return ct;
30 }
31 // -------------------------
32
33
34 template <typename Type>
grep(Type * f,ulong n,bool (* func)(Type))35 inline ulong grep(Type *f, ulong n, bool (* func)(Type))
36 // In place version:
37 // Discard elements for which func() returns false.
38 // Return number of elements kept.
39 {
40 ulong k, j;
41 for (k=0,j=0; j<n; ++k,++j)
42 {
43 f[k] = f[j];
44 if ( func(f[j]) ) --k;
45 }
46 return k;
47 }
48 // -------------------------
49
50
51 template <typename Type>
grep_idx(const Type * f,ulong n,bool (* func)(Type),ulong * x)52 inline ulong grep_idx(const Type *f, ulong n, bool (* func)(Type), ulong *x)
53 // Make x[] the sequence of indices for which func() returns true.
54 // Return number of 'matching' elements found.
55 {
56 ulong ct = 0;
57 for (ulong k=0; k<n; ++k) if ( func(f[k]) ) x[ct++] = k;
58 return ct;
59 }
60 // -------------------------
61
62 #endif // !defined HAVE_GREP_H__
63