This repository has been archived on 2024-01-06. You can view files and clone it, but cannot push or open issues or pull requests.
justhomework/ex11/vector.hpp
2021-12-09 23:04:48 +08:00

158 lines
No EOL
2.1 KiB
C++

#ifndef _VECTOR_HPP_
#define _VECTOR_HPP_
#include <iostream>
template <class T>
class Vector
{
private:
T *_v;
int _len;
int _used;
bool _sorted = false;
void expand();
void shrink();
void adjust();
public:
Vector(int len)
{
_used = 0;
_len = len;
_v = new T[_len];
for (int i = 0; i < _len; i++)
{
_v[i] = NULL;
}
}
Vector()
{
_used = 0;
_len = 10;
_v = new T[_len];
}
~Vector()
{
delete[] _v;
}
T get(int a) { return _v[a]; }
T operator[](int i)
{
while (i >= _len)
{
expand();
}
return _v[i];
}
//排序搜索,返回秩
int search(T value);
//某处更改为某值
void put(int a, T value);
void swap(int a, int b);
int insert(int locate, int value);
int remove(int locate, int value);
int remove_sorted(int value);
int find(int value);
void bubbleSort();
void printall();
int getlen();
int getused();
int count(int value);
void mergeSort(int lo, int hi);
private:
void merge(int lo, int mi, int hi);
};
template <class T>
void Vector<T>::put(int a, T value)
{
while (a >= _len)
{
expand();
}
_used++;
_v[a] = value;
}
template <class T>
int Vector<T>::getused()
{
return _used;
}
template <class T>
void Vector<T>::expand()
{
int old_len = _len;
_len = _len * 2;
T *p = new T[_len];
for (int i = 0; i < old_len; i++)
p[i] = _v[i];
for (int i = old_len; i < _len; i++)
{
p[i] = NULL;
}
delete[] _v;
_v = p;
}
// template <class T>
// void Vector<T>::shrink()
// {
// _len = _len >> 1;
// T *p = new T[_len];
// for (int i = 0; i < _used; i++)
// p[i] = _v[i];
// for (int i = _used; i < _len; i++)
// {
// p[i] = NULL;
// }
// delete[] _v;
// _v = p;
// }
// template <class T>
// void Vector<T>::adjust()
// {
// if (((double)_used / (double)_len) < 0.25)
// shrink();
// else if (((double)_used / (double)_len) > 0.75)
// expand();
// return;
// }
template <class T>
int Vector<T>::search(T e)
{
if (_sorted == false)
return -1;
int i = 0;
for (; i <= _used && _v[i] <= e; i++)
;
return i - 1;
}
#endif