设计数组类模板Array,并实现求范围为2~100的质数
时间: 2024-02-28 16:54:10 浏览: 46
好的,我来为您解答。
以下是Array类的实现:
```c++
template<typename T>
class Array {
public:
Array(int size) {
this->size = size;
data = new T[size];
}
~Array() {
delete[] data;
}
T& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
int getSize() const {
return size;
}
private:
T* data;
int size;
};
```
然后,我们可以利用该模板类实现求范围为2~100的质数:
```c++
#include <iostream>
#include <cmath>
using namespace std;
template<typename T>
class Array {
public:
Array(int size) {
this->size = size;
data = new T[size];
}
~Array() {
delete[] data;
}
T& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
int getSize() const {
return size;
}
private:
T* data;
int size;
};
int main() {
Array<bool> isPrime(99);
for (int i = 2; i <= 100; ++i) {
isPrime[i - 2] = true;
}
for (int i = 2; i <= sqrt(100); ++i) {
if (isPrime[i - 2]) {
for (int j = i * i; j <= 100; j += i) {
isPrime[j - 2] = false;
}
}
}
for (int i = 2; i <= 100; ++i) {
if (isPrime[i - 2]) {
cout << i << " ";
}
}
return 0;
}
```
运行结果:
```
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
```
以上就是对于您问题的解答,希望能够帮到您。
阅读全文