【发布时间】:2015-02-07 19:11:13
【问题描述】:
我的安全数组可以保存任何类型的数据,并且可以根据需要调整大小。我要做的是,如果用户输入的数组大小小于 for 循环中的索引(在本例中为 30),它将自行调整大小。但是它太大了,所以我只有很多零。例如,如果我输入大小 15,它将使其大小为 45,这允许我存储所有数据,但我有多余的空间我不需要。我的 TA 说这对于一个好成绩来说很好,但是因为它还没有到期,所以我想要一个 resize 函数,它可以将数组的大小调整为与索引完全相同的大小,而不管用户输入的大小是多少.我不确定如何最好地做到这一点。有什么帮助吗?谢谢。
#include <iostream>
using namespace std;
template<typename Element>
class SafeArray
{
int size;
Element*Array;
Element def;
public:
SafeArray() //default constructor(with no parameter)
{
Array = new Element[size];
size = 10;
}
SafeArray(int value = NULL) //constructor with one int
{
Array = new Element[value];
size = value;
}
~SafeArray() { delete [] Array;}; //destructor
Element get(int pos) //get method
{ if (pos<0)
{cout<<"error";}
if(pos>=size)
{ set_default(def);}
return Array[pos]; }
void set(int pos, Element val) //set method
{ if (pos<0)
{
cout<<"error";
}
if(pos>=size)
{ resize(3); }
Array[pos] = val; }
void resize(int size_mult) //resize function
{
Element*temp=new Element[size*size_mult];
for(int i = 0; i<size;i++)
{temp[i]=Array[i];}
delete[]Array;
Array = temp;
size=size*size_mult;
}
void set_default(Element d) //set_default(just a safety precaution, doesn't really effect the outcome)
{
def=d;
}
//Element get_default()
// {
// return def;
// }
int get_size() //get size
{
return size;
}
};
int main()
{
int N;
cout<<"How big should the Array be?"<<endl;
cin>>N;
SafeArray<int> X(N);
SafeArray<double>Y(N);
X.set_default(-1);
cout<<"Array is size "<<X.get_size()<<endl;
for(int i=0; i<30;i++)
{
int x=i*3+1;
double y =1000.0/x;
X.set(i,x);
Y.set(i,y);
}
for (int i = 0; i <= X.get_size(); i += 1)
{if(i<10)
cout <<"0"<< i << ": x = " << X.get(i) << ", 1000/x = " << Y.get(i) << "\n";
else
cout << i << ": x = " << X.get(i) << ", 1000/x = " << Y.get(i) << "\n";}
cout<<"Array is size "<<X.get_size()<<endl;
return 0;
}
【问题讨论】:
-
我猜只是交出
std::vector的包装是作弊?肯定是技术上最好的解决方案。 :) -
if(pos>=size) { resize(3); }不安全:如果我创建SafeArray<int> X(10)然后写X.set(100, 1)怎么办? -
是的,我们不允许在此类中使用 std::vector。会很好。
-
@Inspired 是的,这似乎可行,但作为分配标准的一部分,我必须在我的 SafeArray 类中有一个 resize 方法来做到这一点。另外,它仅在索引为 30 时才有效。如果我将其更改为 40,那么它只会将数组大小设置为 90
-
通过
type name(value);创建变量不是一个好主意,因为您实际上并没有创建变量,甚至可能编译器不允许您这样做(或在您这样做时警告您)。这被称为“最令人烦恼的解析”。 C++11 引入了使用 {} 而不是 () 来初始化变量、执行此操作或查找有关如何解决该问题的信息的可能性。