From: Lukas Jiriste Date: Wed, 22 Jan 2025 14:43:34 +0000 (+0100) Subject: Implement solution to ex01 X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=1da5e49fac7c7f1fa1da3fd0bee664af5833d1b2;p=42%2FCPP_Module_07 Implement solution to ex01 --- diff --git a/ex01/Makefile b/ex01/Makefile new file mode 100644 index 0000000..4ab989c --- /dev/null +++ b/ex01/Makefile @@ -0,0 +1,52 @@ +CC := c++ +CFLAGS = -std=c++98 -Wall -Wextra -Werror -Wpedantic + +ifneq ("$(wildcard .debug)","") + CFLAGS += -g +endif + +RM := rm -f + +INCDIR := inc +INCDIR += $(addsuffix /inc, $(SUBPROJECTS)); +ifneq ($(INCLUDE),) + INCLUDE := $(addprefix -I, $(INCDIR)) +endif + +SRCDIR := . + +SOURCES := main.cpp \ + +SOURCES := $(addprefix $(SRCDIR)/, $(SOURCES)) + +OBJECTS := $(SOURCES:.cpp=.o) + +NAME := iter + +all : $(NAME) + +debug : .debug + $(MAKE) all + +nodebug : + $(RM) .debug + $(MAKE) re + +.% : + $(MAKE) fclean + touch $@ + +$(NAME) : $(OBJECTS) + $(CC) $(CFLAGS) -o $@ $^ $(LINKS) + +%.o : %.cpp + $(CC) $(CFLAGS) -o $@ -c $< $(INCLUDE) + +clean : + $(RM) $(OBJECTS) + +fclean : clean + $(RM) $(NAME) + +re : fclean + $(MAKE) all diff --git a/ex01/iter.h b/ex01/iter.h new file mode 100644 index 0000000..54217b9 --- /dev/null +++ b/ex01/iter.h @@ -0,0 +1,15 @@ +#ifndef ITER_H +# define ITER_H + +#include + +typedef std::size_t size_t; + +template +void iter(T *array, size_t size, void (*f)(T &)) +{ + for (size_t i(0); i < size; ++i) + f(array[i]); +} + +#endif // ITER_H diff --git a/ex01/main.cpp b/ex01/main.cpp new file mode 100644 index 0000000..739f755 --- /dev/null +++ b/ex01/main.cpp @@ -0,0 +1,34 @@ +#include "iter.h" +#include + +template +void plus_one(T &num) +{ + num += 1; +} + +void triple(double &d) +{ + d *= 3; +} + +int main(void) +{ + const size_t INT_ARR_SIZE = 5; + const size_t DOUBLE_ARR_SIZE = 7; + int int_arr[INT_ARR_SIZE] = {1, 2, 3, 4, 5}; + double d_arr[DOUBLE_ARR_SIZE] = {0.1, 5.2, 4, 0.123456, 42.42, 1e6, 1e-7}; + + iter(int_arr, INT_ARR_SIZE, plus_one); + iter(d_arr, DOUBLE_ARR_SIZE, triple); + iter(d_arr, DOUBLE_ARR_SIZE, plus_one); + std::cout << "int_arr: "; + for (size_t i(0); i < INT_ARR_SIZE - 1; ++i) + std::cout << int_arr[i] << ", "; + std::cout << int_arr[INT_ARR_SIZE - 1] << '\n'; + std::cout << "d_arr: "; + for (size_t i(0); i < DOUBLE_ARR_SIZE - 1; ++i) + std::cout << d_arr[i] << ", "; + std::cout << d_arr[DOUBLE_ARR_SIZE - 1] << '\n'; + return (0); +}