-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtake_as_argument.cpp
More file actions
56 lines (46 loc) · 1.48 KB
/
take_as_argument.cpp
File metadata and controls
56 lines (46 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "benchmark.h"
#include <iostream>
// How to have lambda function arguments
// AKA write your own <algorithm> !
#include <vector>
#ifdef FUNCTION_POINTER
bool my_any_of (const std::vector<int> & v, bool (*predicate) (int)) {
for (auto it = v.begin (); it != v.end (); ++it)
if (predicate (*it))
return true;
return false;
}
// Fails with stateful lambdas...
#endif
#ifdef STD_FUNCTION
#include <functional>
bool my_any_of (const std::vector<int> & v, std::function<bool(int)> predicate) {
for (auto it = v.begin (); it != v.end (); ++it)
if (predicate (*it))
return true;
return false;
}
// Supports most lambdas, but costly : virtual class and malloc internally
#endif
#ifdef TEMPLATE
template <typename Predicate> bool my_any_of (const std::vector<int> & v, Predicate predicate) {
for (auto it = v.begin (); it != v.end (); ++it)
if (predicate (*it))
return true;
return false;
}
// Supports all lambdas, but template with all template caveats (header only, etc)
#endif
int main () {
std::cout << std::boolalpha;
auto vec = std::vector<int>{1, 2, 3, 4, 5};
// Stateless
std::cout << "my_any_of (is_0) = " << my_any_of (vec, [](int i) { return i == 0; }) << "\n";
std::cout << "my_any_of (is_1) = " << my_any_of (vec, [](int i) { return i == 1; }) << "\n";
// Stateful
int k = 42;
// std::cout << "my_any_of (is_k) = " << my_any_of (vec, [k](int i) { return i == k; }) << "\n";
// Small benchmark
benchmark_predicate_on_non_zero_random_vector (my_any_of);
return 0;
}