以下因错误而失败 prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’
int main()
{
char d = 'd';
std::string y("Hello worl");
y.append(d); // Line 5 - this fails
std::cout << y;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我也试过,以下,编译但在运行时随机行为:
int main()
{
char d[1] = { 'd' };
std::string y("Hello worl");
y.append(d);
std::cout << y;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
抱歉这个愚蠢的问题,但我搜索了谷歌,我能看到的只是"char char to char ptr","char ptr to char array"等.
Ara*_*raK 204
y += d;
Run Code Online (Sandbox Code Playgroud)
我会使用+=
运算符而不是命名函数.
Fer*_*yer 61
用途push_back()
:
std::string y("Hello worl");
y.push_back('d')
std::cout << y;
Run Code Online (Sandbox Code Playgroud)
Pat*_*ola 18
要使用append方法将char添加到std :: string var,您需要使用此重载:
std::string::append(size_type _Count, char _Ch)
Run Code Online (Sandbox Code Playgroud)
编辑:你是对的我误解了上下文帮助中显示的size_type参数.这是要添加的字符数.所以正确的电话是
s.append(1, d);
Run Code Online (Sandbox Code Playgroud)
不
s.append(sizeof(char), d);
Run Code Online (Sandbox Code Playgroud)
或者最简单的方法:
s += d;
Run Code Online (Sandbox Code Playgroud)
Bri*_*ndy 10
除了提到的其他内容之外,其中一个字符串构造函数采用char和该char的重复次数.所以你可以用它来追加一个char.
std::string s = "hell";
s += std::string(1, 'o');
Run Code Online (Sandbox Code Playgroud)
小智 7
我通过将它们运行到一个大循环来测试几个命题.我使用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;
Run Code Online (Sandbox Code Playgroud)
根据这项测试,结果如下:
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'
Run Code Online (Sandbox Code Playgroud)
结论
+=
似乎更容易理解,但如果你关心速度,请使用追加
归档时间: |
|
查看次数: |
286132 次 |
最近记录: |