我有一个程序,使用randomCharacter
函数生成一个随机字符,并使用randomString
函数生成随机字符串。后者利用前者,breedWithMutation
使用randomCharacter
概率性地突变基因序列的表示。
#include <ctime>
#include <boost/random.hpp>
typedef boost::mt19937 randAlgorithm;
int mutationsPerGeneration = 100;
double probabilityOfMutation = 0.05;
string potentialAlleles = "abcdefghijklmnopqrstuvwxyz ";
size_t numberOfAlleles = potentialAlleles.size();
double random01(randAlgorithm & engine)
{
boost::uniform_real<double> u01;
return u01(engine);
}
int randomInteger(randAlgorithm & engine, size_t min, size_t max) {
boost::uniform_int<> minmax(min, max);
return minmax(engine);
}
string randomCharacter(randAlgorithm & engine, string charSet, size_t charSetSize) {
return charSet[randomInteger(engine, 0, charSetSize)];
}
string randomString(randAlgorithm & engine, size_t length, string charSet, size_t charSetSize) {
string s;
s.reserve(length);
for (int i = 0; i < length; i++) {
s.append(randomCharacter(engine, charSet, charSetSize));
}
return s;
}
string breedWithMutation(randAlgorithm & engine, string originalGenome, size_t genomeSize) {
string mutatedGenome;
mutatedGenome.reserve(genomeSize);
double mutationDraw;
for (size_t i = 0; i < genomeSize; i++) {
mutationDraw = random01(engine);
if (mutationDraw < probabilityOfMutation) { //The allele undergoes mutation
mutatedGenome.append(randomCharacter(engine, potentialAlleles, numberOfAlleles));
}
else {
mutatedGenome.append(originalGenome[i]);
}
}
return mutatedGenome;
}
但是,在构建应用程序时,出现以下错误:
main.cpp: In function ‘std::string randomCharacter(randAlgorithm&, std::string, size_t)’:
main.cpp:31:55: error: invalid conversion from ‘char’ to ‘const char*’
main.cpp:31:55: error: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’
main.cpp: In function ‘std::string breedWithMutation(randAlgorithm&, std::string, size_t)’:
main.cpp:53:45: error: invalid conversion from ‘char’ to ‘const char*’
main.cpp:53:45: error: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::append(const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]’
我意识到,错误中的行号排列不完全,但是前两个错误是
randomCharacter
中的唯一一行,而第三个和第四个错误是此行:mutatedGenome.append(originalGenome[i]);
中的breedWithMutation
。是什么导致此错误? 最佳答案
在C++中,char
和string
是截然不同的类型。不能将char
值隐式转换为string
(就像您尝试在randomCharacter
中那样)。
您可以将randomCharacter
的返回类型更改为char
而不是string
,尽管这也可能需要在其他地方进行更改(我没有详细检查您的代码)。
关于c++ - 从 'char'到 'const char*'的无效转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8291007/