Skip to content

C++ #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
31 changes: 31 additions & 0 deletions cpp1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#include <iostream>

constexpr size_t ARRSIZ = 5;

int increment(int n) {
return n + 1;
}

template<size_t N>
void print(const int (&arr)[N]){

for (int i = 0; i < N; ++i)
std::cout << arr[i] << "\n";
std::cout << std::endl;
}

void my_objective(int* arr, const size_t N, int (*f)(int)) {
for (int i = 0; i < N; ++i)
arr[i] = f(arr[i]);
}

int main() {

int arr[ARRSIZ] = {0, 1, 2, 3, 4};
my_objective(arr, ARRSIZ, increment);

print(arr);

std::cin.get();

}
25 changes: 25 additions & 0 deletions cpp2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <iostream>
#include <vector>


void print(const std::vector<int>& vec){
for(const int n : arr)
std::cout << n << "\n";
std::cout << std::endl;
}

void my_objective(std::vector<int>& vec, int (*f)(int)) {
for (int i = 0; i < vec.size(); ++i)
vec[i] = f(vec[i]);
}

int main() {
std::vector<int> vec = {0, 1, 2, 3, 4};

my_objective(vec, [](int n){ return n + 1;});

print(vec);

std::cin.get();

}
25 changes: 25 additions & 0 deletions cpp3.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <iostream>
#include <vector>
#include <functional>

void print(const std::vector<int>& vec){
for(const int n : arr)
std::cout << n << "\n";
std::cout << std::endl;
}

void my_objective(std::vector<int>& vec, const std::function<int(int)>& f) {
for (int i = 0; i < vec.size(); ++i)
vec[i] = f(vec[i]);
}

int main() {
std::vector<int> vec = {0, 1, 2, 3, 4};

my_objective(vec, [&](int n){ return n + 1;});

print(vec);

std::cin.get();

}
34 changes: 34 additions & 0 deletions cpp4.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <iostream>
#include <vector>

struct increment{

int operator()(int n) const{
return n + 1;
}
};


void my_objective(std::vector<int>& vec, const increment& f) {
for (int i = 0; i < vec.size(); ++i)
vec[i] = f(vec[i]);
}

void print(const std::vector<int>& vec){
for(const int n : vec)
std::cout << n << "\n";
std::cout << std::endl;
}


int main() {
std::vector<int> vec = {0, 1, 2, 3, 4};
const increment functor;

my_objective(vec, functor);

print(vec);

std::cin.get();

}