ex02 fixed

This commit is contained in:
Angel Ortigosa Perez
2026-04-08 20:51:29 +02:00
parent ceae775295
commit 317ecbc1f9
3 changed files with 46 additions and 47 deletions

View File

@@ -31,7 +31,7 @@ class Array
~Array();
Array(unsigned int n);
T &operator[](unsigned int n);
T &operator[](int n);
unsigned int size() const;
};

View File

@@ -64,9 +64,9 @@ Array<T>::Array(unsigned int n) : length(n)
}
template <typename T>
T &Array<T>::operator[](unsigned int n)
T &Array<T>::operator[](int n)
{
if (n >= length)
if (n < 0 || (unsigned int)n >= length)
throw std::exception();
return (data[n]);
}

View File

@@ -1,53 +1,52 @@
#include <iostream>
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aortigos <aortigos@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/04/08 20:40:27 by aortigos #+# #+# */
/* Updated: 2026/04/08 20:50:41 by aortigos ### ########.fr */
/* */
/* ************************************************************************** */
#include "Array/Array.hpp"
#define MAX_VAL 750
int main(int, char**)
{
Array<int> numbers(MAX_VAL);
int* mirror = new int[MAX_VAL];
srand(time(NULL));
for (int i = 0; i < MAX_VAL; i++)
{
const int value = rand();
numbers[i] = value;
mirror[i] = value;
}
//SCOPE
{
Array<int> tmp = numbers;
Array<int> test(tmp);
}
Array<int> nb(6);
nb[0] = 0;
nb[1] = 1;
nb[2] = 2;
nb[3] = 3;
for (int i = 0; i < MAX_VAL; i++)
{
if (mirror[i] != numbers[i])
{
std::cerr << "didn't save the same value!!" << std::endl;
return 1;
}
}
try
{
numbers[-2] = 0;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
try
{
numbers[MAX_VAL] = 0;
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
for (int i = 0; i < MAX_VAL; i++)
std::cout << "Imprimiendo array de ints..." << std::endl;
try {
std::cout << "Posicion X: " << nb[5] << std::endl;
} catch(std::exception &e)
{
numbers[i] = rand();
std::cout << e.what() << std::endl;
}
delete [] mirror;//
return 0;
std::cout << "Tamaño: " << nb.size() << std::endl;
Array<std::string> st(6);
st[0] = "as2";
st[1] = "wa1";
st[2] = "lf2";
st[3] = "as3";
st[4] = "xs4";
st[5] = "aj5";
std::cout << std::endl << "Imprimiendo array de strs..." << std::endl;
try {
std::cout << "Posicion X: " << st[4] << std::endl;
} catch(std::exception &e)
{
std::cout << e.what() << std::endl;
}
std::cout << "Tamaño: " << st.size() << std::endl;
}