Implement solution to ex01
authorLukas Jiriste <ljiriste@student.42prague.com>
Wed, 22 Jan 2025 14:43:34 +0000 (15:43 +0100)
committerLukas Jiriste <ljiriste@student.42prague.com>
Wed, 22 Jan 2025 14:43:34 +0000 (15:43 +0100)
ex01/Makefile [new file with mode: 0644]
ex01/iter.h [new file with mode: 0644]
ex01/main.cpp [new file with mode: 0644]

diff --git a/ex01/Makefile b/ex01/Makefile
new file mode 100644 (file)
index 0000000..4ab989c
--- /dev/null
@@ -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 (file)
index 0000000..54217b9
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef ITER_H
+# define ITER_H
+
+#include <cstddef>
+
+typedef std::size_t size_t;
+
+template<typename T>
+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 (file)
index 0000000..739f755
--- /dev/null
@@ -0,0 +1,34 @@
+#include "iter.h"
+#include <iostream>
+
+template<typename T>
+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<int>);
+       iter(d_arr, DOUBLE_ARR_SIZE, triple);
+       iter(d_arr, DOUBLE_ARR_SIZE, plus_one<double>);
+       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);
+}