- Joined
- 11/5/14
- Messages
- 298
- Points
- 53
I removed all dynamic allocations, so the code becomes consistent. The fixed size array is being created at compile time, so I should not use new. Does it still look like a potpourri of C and C++ code..?
Code:
#ifndef QPARRAY_H
#define QPARRAY_H
#include <cstring>
template <class T, std::size_t N>
class QPArray
{
private:
T items[N];
int maxsize;
public:
/*Constructors and destructors*/
QPArray();
QPArray(const T value);
QPArray(const QPArray<T, N>& a);
virtual ~QPArray();
/* Overload = operator*/
QPArray<T, N>& operator =(const QPArray<T, N>& a);
/* Selectors - Element access*/
T& at(int index);
T& operator [](int index);
T& front();
T& back();
/* Capacity*/
bool empty();
virtual int size();
virtual int max_size();
/*Operations*/
QPArray<T, N>& fill(T value);
};
template <class T,std::size_t N>
QPArray<T, N>::QPArray()
{
maxsize = N;
}
template <class T, std::size_t N>
QPArray<T, N>::QPArray(T value)
{
maxsize = N;
if (N > 0)
{
for (int i = 0; i < maxsize; i++)
{
items[i] = value;
}
}
}
template <class T, std::size_t N>
QPArray<T,N>::QPArray(const QPArray<T, N>& a)
{
maxsize = a.maxsize;
for (int i = 0; i < maxsize; i++)
items[i] = a.items[i];
}
template<class T, std::size_t N>
QPArray<T, N>::~QPArray(){}
template<class T, std::size_t N>
QPArray<T, N>& QPArray<T, N>::operator =(const QPArray<T, N>& a)
{
if (this == &a)
return *this;
if (maxsize != a.maxsize)
throw std::runtime_error(std::string("Src and target array bounds do not match"));
for (int i = 0; i < maxsize; i++)
{
items[i] = a.items[i];
}
return *this;
}
template <class T, std::size_t N>
T& QPArray<T, N>::at(int i)
{
return items[i];
}
template <class T, std::size_t N>
T& QPArray<T, N>::operator [](int index)
{
return items[index];
}
//Access the first element of the array
template <class T, size_t N>
T& QPArray<T, N>::front() {
return items[0];
}
//Access the last element of the array
template <class T, std::size_t N>
T& QPArray<T, N>::back() {
return items[maxsize - 1];
}
template <class T, std::size_t N>
bool QPArray<T, N>::empty()
{
if (maxsize == 0)
return true;
else
return false;
}
template <class T, std::size_t N>
int QPArray<T,N>::size()
{
return maxsize;
}
template <class T, std::size_t N>
int QPArray<T, N>::max_size()
{
return maxsize;
}
template <class T, std::size_t N>
QPArray<T, N>& QPArray<T, N>::fill(T value)
{
for (int i = 0; i < maxsize; i++)
{
items[i] = value;
}
return *this;
}
#endif // !ARRAY_H
Last edited: