漫画算法笔记
数组实现
#include <iostream>
#include <stdlib.h>
using namespace std
;
template<typename T
>
class MyArray
{
public:
MyArray(int capacity
)
:_capacity(capacity
)
,_size(0)
{
_data
= new T
[capacity
]();
}
~MyArray()
{
delete[] _data
;
}
T
& operator[](int index
)
{
return _data
[index
];
}
void toString()
{
for (int i
= 0; i
< _size
; ++i
)
{
cout
<< _data
[i
] << " ";
}
cout
<< endl
;
}
void insert(const int &element
, const int &index
)
{
if ( index
< 0 || index
> _size
)
{
throw out_of_range("超出数组实际元素范围!");
}
if (_size
>= _capacity
)
resize();
for ( int i
= _size
- 1; i
>= index
; --i
)
{
_data
[i
+ 1] = _data
[i
];
}
_data
[index
] = element
;
++_size
;
}
T
remove(int index
)
{
if (index
< 0 || index
> _size
)
{
throw out_of_range("超出数组实际元素范围!");
}
T delElement
= _data
[index
];
for ( int i
= index
; i
< _size
- 1; ++i
)
{
_data
[i
] = _data
[i
+ 1];
}
--_size
;
return delElement
;
}
private:
void resize()
{
int newCapacity
= _capacity
* 2;
T
*newData
= new T
[newCapacity
]();
memcpy(newData
, _data
, sizeof(T
) * _capacity
);
delete[] _data
;
_data
= newData
;
_capacity
= newCapacity
;
}
T
* _data
;
int _capacity
;
int _size
;
};
int main(int argc
, char** argv
)
{
auto *arr
= new MyArray
<int>(4);
arr
->insert(3, 0);
arr
->insert(7, 1);
arr
->insert(9, 2);
arr
->insert(5, 3);
arr
->toString();
arr
->insert(6, 1);
arr
->toString();
arr
->remove(1);
arr
->toString();
system("pause");
return 0;
}
转载请注明原文地址: https://lol.8miu.com/read-10654.html