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/ex10/vector.hpp
2021-12-03 15:26:29 +08:00

119 lines
No EOL
1.6 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 int[_len];
}
Vector()
{
_used = 0;
_len = 10;
_v = new int[_len];
}
T get(int a){return _v[a];}
T operator[](int i){return _v[i];}
//排序搜索,返回秩
int search(T value);
void put(int a, int 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>::expand()
{
_len = _len * 2;
T *p = new T[_len];
for (int i = 0; i <= _used; i++)
p[i] = _v[i];
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];
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