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
#define HEADER_VECTOR
#include <cstddef>
template<class T>
class Vector{
public:
Vector();
Vector(size_t capacity);
Vector(size_t capacity, T value);
~Vector();
void Affiche();
void Display();
size_t Size();
size_t Capacity();
void PushBack(T value);
private:
int _value;
T* _values;
size_t _capacity;
size_t _size;
};
#endif //HEADER_VECTOR

View file

@ -3,8 +3,23 @@
int main(void)
{
Vector coolVector;
coolVector.Affiche();
std::cout << "Hello world!" << std::endl;
Vector<int> coolVector;
std::cout << "Actual size:" << coolVector.Size() << "\tCapacity: " << coolVector.Capacity() << 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;
}

View file

@ -1,14 +1,67 @@
#include "../include/vector.h"
#include <cstddef>
#include <iostream>
Vector::Vector()
: _value(1)
{}
Vector::~Vector()
{}
void Vector::Affiche()
template<class T>
Vector<T>::Vector()
: _capacity(1)
, _size(0)
{
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>;