我的safearray可以保存任何类型的数据,并且可以根据需要调整大小。我要设置的是,如果用户输入的数组大小小于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;
}
答案 0 :(得分:0)
有一些事情需要考虑。
注意:我可能明智地乘以2而不是传递倍数,因为你将获得相同的时间效益,但不会在更大的调整大小上产生那么多空间。 (即10,000 * 2 = 20,000 vs 10,000 * 3 = 30,000可以节省您可能不需要的10,000个空格)
现在要真正回答你的问题,最好的方法是从0到索引进行for循环,只需将值复制到新数组中,并使最后一个语句成为新的值分配。见下文
设置将变为:
void set(int pos, Element val) //set method
{ if (pos<0)
{
cout<<"error";
}
if(pos>=size)
{ resize(pos+1); }
Array[pos] = val; }
调整大小将如下所示:
void resize(int new_size) //resize function
{
Element*temp=new Element[new_size];
for(int i = 0; i<new_size;i++)
{temp[i]=Array[i];}
delete[]Array;
Array = temp;
size=new_size;
}
编辑: 如果你不太关心这个空间,想要节省一些时间,并且仍然有一个安全的边界分配(有人在你的问题的评论中指出)你可以使用以下Set方法:< / p>
集:
void set(int pos, Element val) //set method
{ if (pos<0)
{
cout<<"error";
}
if(pos>=size)
{ resize((pos - size) * 2); }
Array[pos] = val; }
这将为您提供一些额外的空间,您可以使用大于2的倍数来获得更好的时间节省(即通过for循环添加)。