在循环构造函数调用中创建的对象的副本
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
。请记住,在大多数平台上,time
函数以秒为单位返回时间,因此,如果您的构造函数在一秒内被调用多次(很可能发生),那么所有这些调用都将调用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
兰特0:5552 28070 20827
时间:1452309502
兰特1:23416 6051 20830
时间:1452309502
兰特2:23416 6051 20830
更多详细信息,参考srand,时间
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象