c++ - 在数组 dna 中的每个对象中获取相同的字符串(基因数组)(动态分配)

标签 c++ pointers dynamic-memory-allocation

我创建了一个名为 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 并使用适当的数字分布。另外,我更改了唯一指针的代码。

Here's a live example .

关于c++ - 在数组 dna 中的每个对象中获取相同的字符串(基因数组)(动态分配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56152712/

相关文章:

java - JNI : return an object from Java to C++, 并将其传递回 Java

pointers - 错误 : forming pointer to reference type 'const std::pair<double, unsigned int>&' . ...我无法理解这个错误

c - 如何将 uint8_t * 复制到 char 数组

请求从 C++ 到非标量类型的转换

c++ - 为什么这个模板类拥有的类的类型,使用模板类型,无法识别?

java - 使用 JNI 问题构建 .so 文件

c++ - 在 C++ 中传递结构时的可选逻辑

c++ - 在 C++ 中,有没有办法从返回类型为 string& 的函数中返回任何内容?

c++ - 在类方法中使用 new 运算符动态分配内存的生命周期和范围是多少?

条件跳转或移动取决于未初始化值/未初始化值是由堆分配 (realloc) 创建的