這個問題我已經不是第一次遇到了,由於不是總編程,所以總會忘記這一點:
在c++中是不允許數組作爲函數的返回值的
所以想要函數返回一個數組,那麼只能返回這個數組的指針,然後在想調用這個數組的函數中新建指針然後調用這個函數。
舉個例子:
//生成含有範圍屬於[begin,end]的188個隨機整數的數組
int *List(int begin, int end)
{
const int sum=188;
int *a= new int[sum];
srand((unsigned)time(NULL));
list<int>::iterator it;//迭代器
list<int> l;//定義鏈表,保存生成的隨機數
if ( (end<0)||(begin<0)||(begin >end)|| (sum>end))//起始範圍必須大於0,且隨機數個數小於等於最大數字範圍
{
cout << "範圍錯誤";
cout << endl;
system("pause");
}
else
{
while (l.size() < sum)
{
l.push_back((rand()*5) % (end - begin + 1) + begin);
l.sort();//排序
l.unique();//去除相鄰的重複隨機數中的第一個
}
}
int i=0;
for (it = l.begin(); it != l.end(); it++)
{
a[i]=*it;
i++;
}
return a;
}
調用
const int dataNum=147456;
int *DataList = List(0,dataNum);
這裏就可以調用到生成的數組。
這個代碼裏有個小細節,是我遇到問題之後解決的
隨機數的生成,大家都知道使用下面的搭配來生成0-100的隨機數:
srand((unsigned)time(NULL))和rand()%100
但是一般很少有人用到去生成很大的隨機數,而在一開始出錯之後,我測試發現:
rand()生成的數值最大是34767,也就是說,如果要像我一樣生成0-147456之間的隨機數,就要進行改變,讓這個rand變得更大。我這裏很偷懶的用了乘5的方法,你們有更好的方法可以告訴我,我這裏需要的沒有那麼精確隨機,所以就這麼用了。