sim_ressorts/labo01/Vector.h

124 lines
3.0 KiB
C
Raw Normal View History

2024-02-27 13:27:05 -05:00
#pragma once
/**
* @file Vector.h
*
* @brief Implémentation de vecteurs simples
*
* Nom: William Nolin
* Code permanent : NOLW76060101
* Email : william.nolin.1@ens.etsmtl.ca
*
*/
#include <cmath>
#include "MatrixBase.h"
namespace gti320 {
/**
* Classe vecteur générique.
*
* Cette classe réutilise la classe `MatrixBase` et ses spécialisations de
* templates pour les manipulation bas niveau.
*/
template<typename _Scalar = double, int _Rows = Dynamic>
class Vector : public MatrixBase<_Scalar, _Rows, 1> {
public:
/**
* Constructeur par défaut
*/
Vector() : MatrixBase<_Scalar, _Rows, 1>() {}
/**
* Contructeur à partir d'un taille (rows).
*/
explicit Vector(int rows) : MatrixBase<_Scalar, _Rows, 1>(rows, 1) {}
/**
* Constructeur de copie
*/
Vector(const Vector &other) : MatrixBase<_Scalar, _Rows, 1>(other) {}
/**
* Constructeur de copie avec une grandeur différente
* @tparam _OtherRows
* @param other
*/
template<int _OtherRows>
Vector(const Vector<_Scalar, _OtherRows> &other) : MatrixBase<_Scalar, _Rows, 1>() {
int n = std::min(other.size(), _Rows);
const _Scalar *src = other.data();
_Scalar *dest = this->m_storage.data();
memcpy(dest, src, n * sizeof(_Scalar));
if (n < _Rows) {
memset(&dest[n], 0, (_Rows - n) * sizeof(_Scalar));
}
}
/**
* Destructeur
*/
~Vector() {}
/**
* Opérateur de copie
*/
Vector &operator=(const Vector &other) {
this->m_storage = other.m_storage;
2024-03-01 17:27:37 -05:00
this->m_rows = other.rows();
2024-02-27 13:27:05 -05:00
return *this;
}
/**
* Accesseur à une entrée du vecteur (lecture seule)
*/
_Scalar operator()(int i) const {
return this->m_storage.data()[i];
}
/**
* Accesseur à une entrée du vecteur (lecture et écriture)
*/
_Scalar &operator()(int i) {
return this->m_storage.data()[i];
}
/**
* Modifie le nombre de lignes du vecteur
*/
void resize(int _rows) {
MatrixBase<_Scalar, _Rows, 1>::resize(_rows, 1);
}
/**
* Produit scalaire de *this et other.
*/
inline _Scalar dot(const Vector &other) const {
assert(this->size() == other.size());
_Scalar product = 0;
for (int i = 0; i < this->size(); i++) {
product += (*this)(i) * other(i);
}
return product;
}
/**
* Retourne la norme euclidienne du vecteur
*/
inline _Scalar norm() const {
_Scalar norm = 0;
for (int i = 0; i < this->size(); i++) {
norm += std::pow((*this)(i), 2);
}
return std::sqrt(norm);
}
};
}