Skip to content

Instantly share code, notes, and snippets.

@yuu
Last active June 21, 2019 00:56
Show Gist options
  • Save yuu/b427417d5c187b44d96ca03387a5bd01 to your computer and use it in GitHub Desktop.
Save yuu/b427417d5c187b44d96ca03387a5bd01 to your computer and use it in GitHub Desktop.
[c++] Higher order functions examples
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>
namespace {
std::vector<int> vec = {1, 2, 3};
void result(bool ret, const char *func) {
printf("%s result: ", func);
if (ret)
printf("true\n");
else
printf("false\n");
}
void transform() {
std::vector<int> out;
std::transform(vec.begin(), vec.end(), std::back_inserter(out), [](int elem) { return elem * 2; });
std::for_each(out.begin(), out.end(), [](auto &&x) { printf("%d\n", x); });
}
void all_of() {
auto ret = std::all_of(vec.begin(), vec.end(), [](auto &&x) {
if (x == 1 || x == 2 || x ==3)
return true;
return false;
});
result(ret, __func__);
ret = std::all_of(vec.begin(), vec.end(), [](auto &&x) {
if (x == 1 || x != 2 || x ==3)
return true;
return false;
});
result(ret, __func__);
}
void any_of() {
auto ret = std::any_of(vec.begin(), vec.end(), [](auto &&x) {
if (x == 1)
return true;
return false;
});
result(ret, __func__);
ret = std::any_of(vec.begin(), vec.end(), [](auto &&x) {
return false;
});
result(ret, __func__);
}
void none_of() {
auto ret = std::none_of(vec.begin(), vec.end(), [](auto &&x) {
return false;
});
result(ret, __func__);
ret = std::none_of(vec.begin(), vec.end(), [](auto &&x) {
if (x == 1)
return true;
return false;
});
result(ret, __func__);
}
// std::for_each skip
/* need clang compiler ...
void for_each_n() {
std::vector<int> vec = {2, 3, 4};
std::for_each_n(vec.begin(), 2, [](auto &x) {
printf("%d\n", x);
});
}
*/
} // namespace
int main(){
//transform();
//all_of();
//any_of();
//none_of();
//for_each_n();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment