Select Git revision
Vector.hpp 3.13 KiB
#ifndef VECTOR_HPP
#define VECTOR_HPP
#include <PugsMacros.hpp>
#include <PugsUtils.hpp>
#include <PugsAssert.hpp>
#include <Array.hpp>
template <typename DataType>
class Vector
{
public:
using data_type = DataType;
using index_type = size_t;
private:
Array<DataType> m_values;
static_assert(std::is_same_v<typename decltype(m_values)::index_type, index_type>);
public:
friend PUGS_INLINE Vector
copy(const Vector& x)
{
auto values = copy(x.m_values);
Vector x_copy{0};
x_copy.m_values = values;
return x_copy;
}
friend std::ostream&
operator<<(std::ostream& os, const Vector<DataType>& x)
{
for (index_type i = 0; i < x.size(); ++i) {
os << i << " : " << x[i] << '\n';
}
return os;
}
friend Vector operator*(const DataType& a, const Vector& x)
{
Vector y = copy(x);
return y *= a;
}
PUGS_INLINE
DataType
operator,(const Vector& y)
{
DataType sum = 0;
// Does not use parallel_for to preserve sum order
for (index_type i = 0; i < this->size(); ++i) {
sum += m_values[i] * y.m_values[i];
}
return sum;
}
PUGS_INLINE
Vector&
operator/=(const DataType& a)
{
const DataType inv_a = 1. / a;
return (*this) *= inv_a;
}
PUGS_INLINE
Vector&
operator*=(const DataType& a)
{
parallel_for(
this->size(), PUGS_LAMBDA(const index_type& i) { m_values[i] *= a; });
return *this;
}
PUGS_INLINE
Vector&
operator-=(const Vector& y)
{
Assert(this->size() == y.size());
parallel_for(
this->size(), PUGS_LAMBDA(const index_type& i) { m_values[i] -= y.m_values[i]; });
return *this;
}
PUGS_INLINE
Vector&
operator+=(const Vector& y)
{
Assert(this->size() == y.size());
parallel_for(
this->size(), PUGS_LAMBDA(const index_type& i) { m_values[i] += y.m_values[i]; });
return *this;
}
PUGS_INLINE
Vector
operator+(const Vector& y) const
{
Assert(this->size() == y.size());
Vector sum{y.size()};
parallel_for(
this->size(), PUGS_LAMBDA(const index_type& i) { sum.m_values[i] = m_values[i] + y.m_values[i]; });
return sum;
}
PUGS_INLINE
Vector
operator-(const Vector& y) const
{
Assert(this->size() == y.size());
Vector sum{y.size()};
parallel_for(
this->size(), PUGS_LAMBDA(const index_type& i) { sum.m_values[i] = m_values[i] - y.m_values[i]; });
return sum;
}
PUGS_INLINE
DataType& operator[](const index_type& i) const noexcept(NO_ASSERT)
{
return m_values[i];
}
PUGS_INLINE
size_t
size() const noexcept
{
return m_values.size();
}
PUGS_INLINE Vector&
operator=(const DataType& value) noexcept
{
m_values.fill(value);
return *this;
}
template <typename DataType2>
PUGS_INLINE Vector&
operator=(const Vector<DataType2>& vector) noexcept
{
m_values = vector.m_values;
return *this;
}
PUGS_INLINE
Vector& operator=(const Vector&) = default;
PUGS_INLINE
Vector& operator=(Vector&&) = default;
Vector(const Vector&) = default;
Vector(Vector&&) = default;
Vector(const size_t& size) : m_values(size) {}
~Vector() = default;
};
#endif // VECTOR_HPP