我在另一个Stack问题中找到了这个:
//https://dev59.com/TXA75IYBdhLWcg3wOGLS
//
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
size_t end_pos = start_pos + from.length();
str.replace(start_pos, end_pos, to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
我的方法:
string convert_FANN_array_to_binary(string fann_array)
{
string result = fann_array;
cout << result << "\n";
replaceAll(result, "-1 ", "0");
cout << result << "\n";
replaceAll(result, "1 ", "1");
return result;
}
针对此输入值的操作是:
cout << convert_FANN_array_to_binary("1 1 -1 -1 1 1 ");
现在,输出应该是"110011"
这是方法的输出:
1 1 -1 -1 1 1 // original
1 1 0 1 // replacing -1's with 0's
11 1 // result, as it was returned from convert_FANN_array_to_binary()
我一直在查看replaceAll代码,但是我真的不确定为什么它会将连续的-1替换为一个0,然后在最终结果中不返回任何0(但是有一些1)。=\