已解决:
它试图告诉我问题
cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'
TL'DR
char* 不是 string...
// Unintended Output
string tester = "foo";
printf("%s <- not foo\n\n", tester);
// Intended Output
char* testerc = "foo";
printf("%s <- foo\n\n", testerc);
结果:
r <- not foo
foo <- foo
对于函数声明:
void func(char* stringParam){} 有效,但是
void func(string stringParam){} 在函数中没有打印出我们想要的内容
printf("%s", stringParam);
为什么?
printf 的字符串插值对%s 使用字符数组,而不是实际字符串。 (也不限于printf,是吗?lmk)
所以解决方案是 使用 c_str() - <string>.c_str() 为函数参数指定正确的对象类型来转换字符串。如果由于某种原因你不能这样做,也许演员阵容会对你有所帮助。
如果有人想在microseconds 中为快速函数计时并报告它们的持续时间(s、ms、μs 和 ns 都在chrono 的duration_cast 中工作),这就是驱动用例:
int timer (int (*func)(int), int n, char* label){
auto t1 = std::chrono::steady_clock::now().time_since_epoch();
(*func)(n);
auto t2 = std::chrono::steady_clock::now().time_since_epoch();
auto dur = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();
printf("Approach: %s: %d μs for %d iterations\n", label, dur, n);
return dur;
}
现在正确输出:
Approach: Lookups: 588 μs for 32000 iterations
Approach: IF-calcs: 962 μs for 32000 iterations
对于使用任意函数的调用:
int lookupTime = timer(lookupBuzz, iterations, "Lookups");
int calcTime = timer(calcbuzz, iterations, "IF-calcs");
读者:有什么更好的计时方法?在前 n 个整数上运行 fizzbuzz 的最快方法应该是什么?保存结果的最佳方法是什么?后者使用基本数组 - results[x]=fizzbuzz(x); - 似乎有限制,这就是为什么我只为 n 使用 32000,但我想使用 10M 作为基准。)