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/DataStructure/Code/ex11/vector.hpp

160 lines
2.2 KiB
C++
Raw Normal View History

2021-12-09 14:58:46 +00:00
#ifndef _VECTOR_HPP_
#define _VECTOR_HPP_
#include <iostream>
template <class T>
class Vector
{
2021-12-09 16:34:32 +00:00
public:
2021-12-09 14:58:46 +00:00
T *_v;
int _len;
int _used;
bool _sorted = false;
void expand();
void shrink();
void adjust();
2021-12-09 15:04:48 +00:00
public:
2021-12-09 14:58:46 +00:00
Vector(int len)
{
_used = 0;
_len = len;
_v = new T[_len];
for (int i = 0; i < _len; i++)
{
_v[i] = NULL;
}
}
Vector()
{
_used = 0;
2021-12-10 08:51:43 +00:00
_len = 10;
2021-12-09 14:58:46 +00:00
_v = new T[_len];
2021-12-10 01:20:41 +00:00
for (int i = 0; i < _len; i++)
{
_v[i] = 0;
}
2021-12-09 14:58:46 +00:00
}
2021-12-10 01:20:41 +00:00
// ~Vector()
// {
// delete[] _v;
// }
2021-12-09 14:58:46 +00:00
T get(int a) { return _v[a]; }
2021-12-09 16:34:32 +00:00
T operator[](int i) const
2021-12-09 14:58:46 +00:00
{
2021-12-09 16:34:32 +00:00
if(i>=_len)
return 0;
2021-12-09 14:58:46 +00:00
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)
{
2021-12-09 16:34:32 +00:00
// while (a >= _len)
// {
// expand();
// }
2021-12-09 14:58:46 +00:00
_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++)
{
2021-12-09 16:34:32 +00:00
p[i] = 0;
2021-12-09 14:58:46 +00:00
}
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