下面的代码会出现错误prog.cpp:5:13: error:无效的从' char '到' const char* '的转换
int main()
{
char d = 'd';
std::string y("Hello worl");
y.append(d); // Line 5 - this fails
std::cout << y;
return 0;
}
我也尝试了,下面,它编译,但在运行时随机行为:
int main()
{
char d[1] = { 'd' };
std::string y("Hello worl");
y.append(d);
std::cout << y;
return 0;
}
对不起,这个愚蠢的问题,但我已经搜索了谷歌,我能看到的只是“字符数组到字符ptr”,“字符ptr到字符数组”,等等。
我通过将它们运行到一个大循环中来测试这几个命题。
我使用microsoft visual studio 2015作为编译器,我的处理器是i7, 8Hz, 2GHz。
long start = clock();
int a = 0;
//100000000
std::string ret;
for (int i = 0; i < 60000000; i++)
{
ret.append(1, ' ');
//ret += ' ';
//ret.push_back(' ');
//ret.insert(ret.end(), 1, ' ');
//ret.resize(ret.size() + 1, ' ');
}
long stop = clock();
long test = stop - start;
return 0;
根据本次试验,结果为:
operation time(ms) note
------------------------------------------------------------------------
append 66015
+= 67328 1.02 time slower than 'append'
resize 83867 1.27 time slower than 'append'
push_back & insert 90000 more than 1.36 time slower than 'append'
结论
+=似乎更容易理解,但如果您介意速度,请使用append