160 lines
No EOL
2.2 KiB
C++
160 lines
No EOL
2.2 KiB
C++
#ifndef _VECTOR_HPP_
|
|
#define _VECTOR_HPP_
|
|
|
|
#include <iostream>
|
|
|
|
template <class T>
|
|
class Vector
|
|
{
|
|
public:
|
|
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 = 100;
|
|
_v = new T[_len];
|
|
for (int i = 0; i < _len; i++)
|
|
{
|
|
_v[i] = 0;
|
|
}
|
|
}
|
|
// ~Vector()
|
|
// {
|
|
// delete[] _v;
|
|
// }
|
|
|
|
T get(int a) { return _v[a]; }
|
|
T operator[](int i) const
|
|
{
|
|
if(i>=_len)
|
|
return 0;
|
|
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] = 0;
|
|
}
|
|
|
|
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 |