[英]c++ - duplicates of objects created in looped constructor call
我已經定義了一個類,然后使用數組中的構造函數創建它的實例。 由於某種原因,這只會創建實例,盡管所有實例都是隨機的,但其中很多最終都具有完全相同的屬性。 這是構造函數。
class fNNGA: public fNN
{
public:
fNNGA()
{
}
fNNGA(int n)
{
int i;
_node.resize(n);
for(i = 0; i < n; i++)
{
_node[i]._activation = -1;
}
}
fNNGA(int n, int inp, int out, int edge)
{
int i,u,v;
_node.resize(n);
for(i = 0; i < n; i++)
{
_node[i]._activation = 1;
}
for(i = 0; i < inp; i++)
{
setInput(i);
}
for(i = n - out; i < n; i++)
{
setOutput(i);
}
for(i = 0; i < edge; i++)
{
v = rand() % (n - inp) + inp;
u = rand() % v;
setEdge(u,v);
}
init();
}
};
這些是我嘗試創建數組的一些方法:
fNNGA pop[SIZE];
int main()
{
for(int i = 0; i < SIZE; i++)
{
pop[i] = fNNGA(100,16,8,800);
}
}
,
fNNGA *pop[SIZE];
int main()
{
for(int i = 0; i < SIZE; i++)
{
pop[i] = new fNNGA(100,16,8,800);
}
}
,
fNNGA *pop = new fNNGA[SIZE];
int main()
{
for(int i = 0; i < SIZE; i++)
{
new(pop[i]) fNNGA(100,16,8,800);
}
}
如何正確創建這些對象?
不要在構造srand
中調用srand
。 請記住,在大多數平台上, time
函數以秒為單位返回時間,因此,如果在一秒鍾內(很可能發生)多次調用構造srand
,那么所有這些調用都將調用srand
並設置完全相同的種子。
僅在程序開始時調用一次 srand
。 或使用C ++ 11中引入的新的偽隨機數生成類 。
首先,如果您的程序在一秒鍾內運行,則您不能使用srand
來表示time(null)
所有結果都相同。 此外,每次將rand()種子植入相同的種子時,它必須產生相同的值序列。
我的測試代碼和輸出如下:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
#define null 0
int main(int argc, char const *argv[])
{
srand(time(null));
cout << "time:" << time(null) << endl;
cout << "rand 0:" << rand() << " " << rand() << " " << rand() << endl << endl;
//to make the program run for more than a second
for (int i = 0; i < 100000000; ++i)
{
int t = 0;
t = t / 3;
t = t / 3;
t = t / 3;
t = t / 3;
t = t / 3;
t = t / 3;
t = t / 3;
}
srand(time(null));
cout << "time:" << time(null) << endl;
cout << "rand 1:" << rand() << " " << rand() << " " << rand() << endl << endl;
srand(time(null));
cout << "time:" << time(null) << endl;
cout << "rand 2:" << rand() << " " << rand() << " " << rand() << endl;
return 0;
}
輸出:
時間:1452309501
rand 0:5552 28070 20827
時間:1452309502
蘭德1:23416 6051 20830
時間:1452309502
蘭德2:23416 6051 20830
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.