edelib 2.1.0
Functional.h
1/*
2 * $Id: List.h 2839 2009-09-28 11:36:20Z karijes $
3 *
4 * Functional approach for lists
5 * Copyright (c) 2005-2011 edelib authors
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this library. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21#ifndef __EDELIB_FUNCTIONAL_H__
22#define __EDELIB_FUNCTIONAL_H__
23
24#include "Debug.h"
25
26EDELIB_NS_BEGIN
27
37template <typename T, typename F>
38unsigned int filter(const F& func, const T& container, T& ret) {
39 typename T::const_iterator it = container.begin();
40 typename T::const_iterator ite = container.end();
41
42 for(; it != ite; ++it) {
43 if(func(*it))
44 ret.push_back(*it);
45 }
46
47 return ret.size();
48}
49
54template <typename T, typename F>
55void map(F& func, const T& container, T& ret) {
56 typename T::const_iterator it = container.begin();
57 typename T::const_iterator ite = container.end();
58
59 for(; it != ite; ++it)
60 ret.push_back(func(*it));
61}
62
78template <typename T, typename R, typename F>
79void reduce(F& func, const T& container, R& ret) {
80 unsigned int sz = container.size();
81 if(sz == 0) {
82 // nothing
83 } else if(sz == 1)
84 ret = *container.begin();
85 else {
86 typename T::const_iterator it = container.begin();
87 typename T::const_iterator it2 = it;
88 ++it2;
89 typename T::const_iterator ite = container.end();
90
91 ret = func(*it, *it2);
92 for(++it2; it2 != ite; ++it2)
93 ret = func(*it2, ret);
94 }
95}
96
101template <typename T, typename F>
102void for_each(const F& func, const T& container) {
103 typename T::const_iterator it = container.begin();
104 typename T::const_iterator ite = container.end();
105
106 for(; it != ite; ++it)
107 func(*it);
108}
109
115template <typename T, typename F>
116void for_each(const F& func, const T& container, void* p) {
117 typename T::const_iterator it = container.begin();
118 typename T::const_iterator ite = container.end();
119
120 for(; it != ite; ++it)
121 func(*it, p);
122}
123
124EDELIB_NS_END
125#endif
unsigned int filter(const F &func, const T &container, T &ret)
Definition: Functional.h:38
void for_each(const F &func, const T &container, void *p)
Definition: Functional.h:116
void map(F &func, const T &container, T &ret)
Definition: Functional.h:55
void reduce(F &func, const T &container, R &ret)
Definition: Functional.h:79