我的safearray可以容納任何類型的數據,如果需要可以調整大小。我所要做的就是如果用戶輸入的數組大小小於for循環中的索引(本例中爲30),它將自行調整大小。但是它太大了,所以我只有很多零。例如,如果我輸入大小15,它將使它的大小爲45,這允許我存儲所有的數據,但我有額外的空間,我不需要。我的TA說這對於一個好的成績來說很好,但是因爲這不是一兩天的時間,所以我希望有一個調整大小的函數,將數組的大小調整爲與索引大小完全一致,而不管用戶輸入的大小是多少。我不知道如何最好地做到這一點。任何幫助?謝謝。靈活的安全數組C++
#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'的包裝會是作弊嗎?肯定會是技術上最好的解決方案。 :) – 2015-02-07 19:15:47
'if(pos> = size){resize(3); }'不安全:如果我創建'SafeArray X(10)'然後寫入'X.設置(100,1)'? –
Inspired
2015-02-07 19:16:23
是的,我們不允許在這個類中使用std :: vector。會好的。 – dudicus 2015-02-07 19:17:33