目标:
使用动态数组类,动态分配空间并填入数字 使用对象生成并存放指定范围内的素数
代码:
#include <iostream>
using namespace std;
class Array
{
int *s;
int count;
int length;
public:
Array() : length(0), s(nullptr), count(0){};
void gen(int limit)
{
for (int i = 2; i <= limit; i++)
{
int flag = 1;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
flag = 0;
break;
}
}
if (flag)
{
if (s == nullptr)
{
s = new int[2];
length = 2;
}
if (count >= length)
{
int *s_new = new int[length * 2];
memcpy(s_new, s, sizeof(int) * length);
length *= 2;
delete s;
s = s_new;
}
s[count++] = i;
}
}
}
void print(){
for (int i = 0; i < count; i++)
{
cout<<s[i]<<" ";
}
}
};
int main(int argc, char const *argv[])
{
Array a;
a.gen(100);
a.print();
}
评价
掌握好类中动态分配空间的创建,复制与回收过程即可
|