废话不多说,上代码:
myvec.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
#define LENGTH 100
class myvec
{
public:
myvec();
~myvec();
private:
int nCount; //用于记录当前数组插入数据计数
int nLen; //数组实际长度
int *arr; //数组
int *getmem(); //当数据
public:
int insertVec(int data); //插入
int deleteVec(); //删除
int updateVec(int pos); //修改
int at(int i); //访问
int nSize();
};
myvec.cpp
#include "myvec.h"
myvec::myvec()
{
arr = new int[LENGTH]();
nLen = LENGTH;
nCount = 0;
}
myvec::~myvec()
{
delete []arr;
arr = NULL;
}
int *myvec::getmem() //当数据
{
if (nCount >= nLen / 2) { //如果当数组实际插入数据已经到达数组长度的一半,就开始申请当前数组长度一半的数据
nLen = nLen + nLen / 2;
int* tmp = new int[nLen]();
memcpy(tmp, arr, nCount*4);
delete []arr;
arr = tmp;
}
return arr;
}
int myvec::insertVec(int data) //插入
{
arr = getmem();
arr[nCount++] = data;
return 1;
}
int myvec::deleteVec() //删除
{
if (nCount < 1)
return 0;
arr[nCount] = 0;
nCount--;
}
int myvec::updateVec(int pos) //修改
{
return 0;
}
int myvec::at(int i) //访问
{
if (i > nCount || i < 0)
return 0;
return arr[i - 1];
}
int myvec::nSize()
{
return nCount;
}
main.cpp
#include "myvec.h"
int main()
{
myvec vec;
for (int i = 0; i < 40; i++)
vec.insertVec(i);
for (int i = 1; i <= vec.nSize(); i++){
cout << vec.at(i) << " ";
if (i % 10 == 0 && i > 0)
cout << endl;
}
for (int i = 0; i < 80; i++)
vec.insertVec(i + 40);
for (int i = 1; i <= vec.nSize(); i++) {
cout << vec.at(i) << " ";
if (i % 10 == 0 && i > 0)
cout << endl;
}
for (int i = 0; i < 30; i++) {
vec.deleteVec();
}
cout << "------------------------------------------------------------------" << endl;
for (int i = 1; i <= vec.nSize(); i++) {
cout << vec.at(i) << " ";
if (i % 10 == 0 && i > 0)
cout << endl;
}
return 0;
}