自定义向量模板类(Custom Vector)
customVector.h
#pragma once
#include <iostream>
namespace MyCustromVector {
template<typename T, unsigned Size>
class Vector
{
public:
typedef T* Iterator;
Vector(T val = T{
});
Vector(const Vector<T, Size>& src); // copy constructor
Vector(Vector<T, Size>&& src) = delete;
~Vector();
Vector<T, Size>& operator=(Vector<T, Size>& rh); // copy assignment operator
Vector<T, Size>& operator=(Vector<T, Size>&& rh) = delete;
T& operator[](unsigned idx) const
{
if(idx < cSize)
return *(pData + idx);
std::cout << "ERROR! accessing element outside the range!\n";
static T dummyValue{
}; // this is needed to return a reference
return dummyValue;
}
void push(T val); // pushing val to the end of the vector
void push_front(T val);
void insert(unsigned pos, T val);
T back() const
{
if(cSize > 0)
return pData[cSize - 1];
std::cout << "Error! accessing back() when vector is empty!\n";
return T{
};
}
void erase(unsigned pos); // erase element at index pos. Elements after pos should shift left to replace the gap.
void pop(); // pops the back element
void pop_front(); // same as above, but pop from front of the vector
Iterator begin() {
return pData; }
Iterator end() {
return pData + cSize; }
unsigned size() const {
return cSize; }
unsigned capacity() const {
return maxSize; }
bool empty() const {
return cSize == 0; }
unsigned GetSortState() const {
return mStateSort; };
// utility functions:
template<typename Comparator = std::less<T>>
void ascendingsort()
{
for (int k = 1; k < cSize; ++k)
{
T temp = pData[k];
int i = k;
while (i > 0 && pData[i - 1] >= temp)
{
pData[i] = pData[i - 1];
--i;
}
pData[i] = temp;
}
mStateSort = 1;
//std::sort(begin(), end(),Comparator());
}
template<typename Comparator = std::greater<T>>
void descendingsort()
{
for (int k = 1; k < cSize; ++k)
{
T temp = pData[k];
int i = k;
while (i > 0 && pData[i - 1] <= temp)
{
pData[i] = pData[i - 1];
--i;
}
pData[i] = temp;
}
//std::sort(begin(), end(), Comparator());
mStateSort = 2;
}
// returns index of the val, if it is found. If not found, return -1
int search(T val);
int binsearchup(Iterator Data, int start, int end, T val);
int binsearchdown(Iterator Data, int start, int end, T val);
void Find(T val);
private:
unsigned maxSize{
Size }; // Max number of elements we can have in the vector
unsigned cSize{
0}; // current number of elements in the vector
Iterator pData;
bool expand();
void shrink();
unsigned mStateSort{
0 };
};
template<typename T, unsigned B>
std::ostream& operator<<(std::ostream& os, const Vector<T, B>& a)
{
os << "Vector content: " << "[Sort State: " << a.GetSortState() <<
"]" << std::endl;
for (unsigned i = 0; i < a.size(); ++i)
{
os << a[i] << ", ";
}
os << std::endl;
return os;
}
template<typename T, unsigned Size>
Vector<T, Size>::Vector(T val): maxSize(Size), cSize(0),