我创建了一个名为 DNA 的类,它有一个无参数构造函数和两个成员函数,即 initialize() 和 show()。问题是当我创建一个 使用 new 运算符的数组并使用 for 循环调用每个对象的初始化函数,而不是在成员变量“genes”中获取不同的字符串,我在每个对象的基因中获取完全相同的字符集(数组)阵列。尽管我在字符串初始化之前对 srand() 函数进行了播种,但没有看到任何效果。
下面的代码。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
string sampleSpace("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz");
class DNA {
private:
int length;
char *genes;
public:
DNA() {
length = 0;
genes = new char[length];
}
void initialize(int len) {
srand(unsigned(time(NULL)));
this -> length = len;
delete genes;
this -> genes = new char[length];
for (int i = 0; i < length; i++) {
*(genes + i) = sampleSpace.at(rand() % sampleSpace.length());
}
}
void show() {
for (int i = 0; i < length; i++) {
cout<<*(genes + i);
}
cout<<endl;
}
};
int main() {
DNA *dna = new DNA[10];
DNA *temp = dna;
for (int i = 0; i < 10; i++) {
(*temp).initialize(10);
temp++;
}
temp = dna;
for (int i = 0; i < 10; i++) {
(*temp).show();
temp++;
}
return 0;
}
最佳答案
您应该使用新的随机 API 并使用适当的随机引擎:
class DNA {
private:
int length;
std::unique_ptr<char[]> genes;
static std::default_random_engine random;
public:
DNA() : length{0}, genes{} {}
void initialize(int len) {
this-> length = len;
this-> genes = std::make_unique<char[]>(length);
std::uniform_int_distribution<std::size_t> distribution{0, sampleSpace.size() - 1};
for (int i = 0; i < length; i++) {
genes[i] = sampleSpace.at(distribution(random));
}
}
void show() {
for (int i = 0; i < length; i++) {
cout<<genes[i];
}
cout<<endl;
}
};
这将初始化一个 std::default_random_engine
并使用适当的数字分布。另外,我更改了唯一指针的代码。
关于c++ - 在数组 dna 中的每个对象中获取相同的字符串(基因数组)(动态分配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56152712/