我有一個程序,它使用randomCharacter
函數和隨機字符串,使用randomString
函數生成一個隨機字符。後者利用前者,並且breedWithMutation
使用randomCharacter
來概率地突變基因序列的表示。從'char'到'const char *'的轉換無效
#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]);
in breedWithMutation
。什麼導致了這個錯誤?
就我而言,這是一個很差的函數名稱選擇。我可以將一個'char'追加到'string'嗎?我意識到他們是明顯不同的類型;我像我一樣命名了'randomCharacter',因爲它只返回一個字母(從外行人的角度來看,而不是C++的意思)。 等待,'string [index]'返回一個'char'或'string'類型嗎?這是問題嗎? –
@pythonscript'string [index]'的返回類型是char。這確實會導致你的問題。 – fefe