From: Lukas Jiriste Date: Thu, 23 Jan 2025 13:47:37 +0000 (+0100) Subject: Solve ex00 X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;p=42%2FCPP_Module_08 Solve ex00 --- diff --git a/ex00/Makefile b/ex00/Makefile new file mode 100644 index 0000000..93aec28 --- /dev/null +++ b/ex00/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 := easyfind + +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/ex00/easyfind.h b/ex00/easyfind.h new file mode 100644 index 0000000..9957b25 --- /dev/null +++ b/ex00/easyfind.h @@ -0,0 +1,18 @@ +#ifndef EASYFIND_H +# define EASYFIND_H + +# include + +template +int *easyfind(T &int_haystack, int needle) +{ + typename T::iterator begin(int_haystack.begin()); + typename T::iterator end(int_haystack.end()); + typename T::iterator found(std::find(begin, end, needle)); + + if (found == end) + return (NULL); + return (&(*found)); +} + +#endif // EASYFIND_H diff --git a/ex00/main.cpp b/ex00/main.cpp new file mode 100644 index 0000000..a5222e1 --- /dev/null +++ b/ex00/main.cpp @@ -0,0 +1,34 @@ +#include "easyfind.h" +#include +#include +#include +#include + +template +void test_easyfind(T &cont, int needle) +{ + const int *found(easyfind(cont, needle)); + + if (found) + std::cout + << "Found needle " << needle + << " at address " << found << '\n'; + else + std::cout << "Needle " << needle << " not found.\n"; +} + +int main(void) +{ + std::vector vec; + std::list list; + + for (int i(0); i < 5; ++i) + { + vec.push_back(i); + list.push_back(2 * i + 5); + } + test_easyfind(vec, 3); + test_easyfind(list, 3); + test_easyfind(list, 7); + return (0); +}