#include <bits/stdc++.h>
using namespace std;
bool compare(int a, int b)
{
return a > b;
}
void ans(int x, int y, bool (&func)(int a, int b))
{
(func(x, y)) ? cout << x << " is bigger than" << y : cout << y << " is bigger than " << x << endl;
}
int main()
{
ans(10, 20, compare);
return 0;
/*
* https://stackoverflow.com/questions/9410/how-do-you-pass-a-function-as-a-parameter-in-c
*/
//! How to use function as argument or pass a function as parameter in in C++
#include <bits/stdc++.h>
using namespace std;
bool compare(int a, int b)
{
return a > b;
}
//! Way 01
void Way1(int x, int y, bool (&compare)(int a, int b))
{
(compare(x, y)) ? cout << x << " is bigger than " << y : cout << y << " is bigger than " << x << endl;
}
//! Way 02
void Way2(int a, int b, void (*Way1)(int, int, bool (&func)(int a, int b)))
{
Way1(a, b, compare);
}
//! Way 03
/* Default argument isn't allowed to be passed */
void Way3(int p, int q, function<void(int, int, void (*Way1)(int, int, bool (&func)(int a, int b)))> Way2)
{
Way2(p, q, Way1);
}
int main()
{
Way3(200, 100, Way2);
return 0;
}
#include <vector>
#include <algorithm>
#include <iostream>
void transform(std::vector<int>::iterator beginIt,
std::vector<int>::iterator endIt,
std::vector<int>::iterator destinationBeginIt,
int func (int)) {
while (beginIt != endIt) {
*destinationBeginIt = func(*beginIt);
beginIt++;
destinationBeginIt++;
}
}
int main() {
std::vector<int> numbers{1, 2, 3}; // numbers has 3 values: 1, 2, 3
std::vector<int> bigNumbers(3); // bigNumbers has 3 values, default
// initialized: 0, 0, 0
transform(
numbers.begin(),
numbers.end(),
bigNumbers.begin(),
[](int small) {
return small * 10;
}
);
// Print the values of bigNumbers
for (const auto big : bigNumbers) {
std::cout << big << std::endl;
}
}