通过构造函数制作的所有对象都具有相同的向量
我是C ++的新手,我正在尝试创建一种基本的遗传算法.我创建了一个染色体类,并希望创建一个Society类,该类使用随机生成的基因"生成这些染色体的向量.基因是染色体中的向量,其值为0或1.我正在测试染色体的构造函数,并且所有对象都具有相同的基因向量.如何使构造函数生成随机值?我在下面包含了代码.任何其他编码实践或优化技巧也将不胜感激.
I'm new to C++ and I am trying to create a basic genetic algorithm. I created a Chromosome class and want to create a Society class that generates a vector of these Chromosomes with randomly generated "genes". Genes being the vector in the Chromosome that holds values of 0 or 1. I was testing out the Chromosome constructor, and all of the objects have the same gene vectors. How can I make the constructor generate random values? I have included code below. Any other coding practice or optimization tips would also be extremely appreciated.
Source.cpp
Source.cpp
#include "Chromosome.h"
#include "Society.h"
using namespace std;
int main()
{
Chromosome demo = Chromosome::Chromosome();
Chromosome demo2 = Chromosome::Chromosome();
return 1;
}
Chromosome.h
Chromosome.h
#pragma once
#include <vector>
using namespace std;
class Chromosome
{
private:
int fitness;
vector<int> genes;
public:
Chromosome();
void generateGenes();
int calculateFitness(),
getFitness();
vector<int> getGenes();
void setGenes(vector<int> child);
};
Chromosome.cpp
Chromosome.cpp
#include "Chromosome.h"
#include <cstdlib>
#include <ctime>
#include <numeric>
using namespace std;
Chromosome::Chromosome()
{
generateGenes();
Chromosome::fitness = calculateFitness();
}
void Chromosome::generateGenes()
{
srand(time(NULL));
for (unsigned i = 0; i < 10; i++)
{
unsigned chance = rand() % 5;
Chromosome::genes.push_back((!chance)? 1 : 0);
}
}
int Chromosome::calculateFitness()
{
int sum = 0;
for (unsigned i = 0; i < Chromosome::genes.size(); i++)
{
sum += Chromosome::genes[i];
}
return sum;
}
int Chromosome::getFitness()
{
return Chromosome::fitness;
}
vector<int> Chromosome::getGenes()
{
return Chromosome::genes;
}
void Chromosome::setGenes(vector<int> child)
{
Chromosome::genes = child;
}
您将具有相同值 time(NULL)
的随机数生成器作为种子.彼此之后的两个呼叫将返回相同的 time_t
.您将首先生成一组随机数,然后重置随机数生成器并再次生成它们.
You seed the random number generator with the same value time(NULL)
.
Two calls after eachother will return the same time_t
. You'll generate one set of random numbers first, then reset the random number generator and generate them again.
在整个程序运行期间仅调用 srand()
一次.
Only call srand()
once during the whole program run.
此外,请使用 < random>
而是获得更好/更快的随机数生成器.
Also, use <random>
instead to get better/faster random number generators.
使用< random>
代替 rand()%5;
:
#include <random>
// A function to return a random number generator.
inline std::mt19937& generator() {
// the generator will only be seeded once since it's static
static std::mt19937 gen(std::random_device{}());
return gen;
}
// A function to generate unsigned int:s in the range [min, max]
int my_rand(unsigned min, unsigned max) {
std::uniform_int_distribution<unsigned > dist(min, max);
return dist(generator());
}
然后称呼它:
unsigned chance = my_rand(0, 4);