TD1 Question 1

This commit is contained in:
Yohan Boujon 2023-09-25 12:04:16 +02:00
parent f299a902e8
commit ef7c7406c9
3 changed files with 93 additions and 15 deletions

View file

@ -1,13 +1,23 @@
#ifndef HEADER_VECTOR #ifndef HEADER_VECTOR
#define HEADER_VECTOR #define HEADER_VECTOR
#include <cstddef>
template<class T>
class Vector{ class Vector{
public: public:
Vector(); Vector();
Vector(size_t capacity);
Vector(size_t capacity, T value);
~Vector(); ~Vector();
void Affiche(); void Display();
size_t Size();
size_t Capacity();
void PushBack(T value);
private: private:
int _value; T* _values;
size_t _capacity;
size_t _size;
}; };
#endif //HEADER_VECTOR #endif //HEADER_VECTOR

View file

@ -3,8 +3,23 @@
int main(void) int main(void)
{ {
Vector coolVector; Vector<int> coolVector;
coolVector.Affiche(); std::cout << "Actual size:" << coolVector.Size() << "\tCapacity: " << coolVector.Capacity() << std::endl;
std::cout << "Hello world!" << std::endl; coolVector.Display();
coolVector.PushBack(123);
coolVector.Display();
std::cout << "Actual size:" << coolVector.Size() << "\tCapacity: " << coolVector.Capacity() << std::endl;
coolVector.PushBack(124);
coolVector.Display();
std::cout << "Actual size:" << coolVector.Size() << "\tCapacity: " << coolVector.Capacity() << std::endl;
coolVector.PushBack(125);
coolVector.Display();
std::cout << "Actual size:" << coolVector.Size() << "\tCapacity: " << coolVector.Capacity() << std::endl;
coolVector.PushBack(126);
coolVector.Display();
std::cout << "Actual size:" << coolVector.Size() << "\tCapacity: " << coolVector.Capacity() << std::endl;
Vector<float> anotherCoolVector(10,1.2);
anotherCoolVector.Display();
return 0; return 0;
} }

View file

@ -1,14 +1,67 @@
#include "../include/vector.h" #include "../include/vector.h"
#include <cstddef>
#include <iostream> #include <iostream>
Vector::Vector() template<class T>
: _value(1) Vector<T>::Vector()
{} : _capacity(1)
, _size(0)
Vector::~Vector()
{}
void Vector::Affiche()
{ {
std::cout << "Vector: " << _value << std::endl; _values = new T[1];
} }
template<class T>
Vector<T>::Vector(size_t capacity)
: _capacity(capacity)
, _size(0)
{
_values = new T[capacity];
}
template<class T>
Vector<T>::Vector(size_t capacity, T value)
: _capacity(capacity)
, _size(capacity)
{
_values = new T[capacity];
for(size_t i = 0; i<capacity; i++)
_values[i] = value;
}
template<class T>
Vector<T>::~Vector()
{
delete[] _values;
}
template<class T>
void Vector<T>::Display()
{
for(size_t i = 0; i<_size; i++)
std::cout << _values[i] << std::endl;
}
template<class T>
size_t Vector<T>::Capacity() { return _capacity; }
template<class T>
size_t Vector<T>::Size() { return _size; }
template<class T>
void Vector<T>::PushBack(T value)
{
if (_capacity < _size+1)
{
T* oldPtr = _values;
_values = new T[_size*2];
_capacity*=2;
for(size_t i=0; i<_size; i++)
_values[i] = oldPtr[i];
delete[] oldPtr;
}
_values[_size] = value;
_size++;
}
template class Vector<int>;
template class Vector<float>;