且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

最优雅的方式来初始化一个字符串与一个字符从另一个字符串

更新时间:2022-11-16 16:19:55

您提及的构造函数 >从一个字符创建字符串的方式,所以没有一个明显更优雅的方式。但是,没有必要创建和复制/移动临时文件:

The constructor you mention is the way to create a string from one character, so there won't be a significantly more elegant way. However, there's no need to create and copy/move a temporary:

string second(1, first[0]);

或者,您可以从的子字符串

string second(first, 0, 1);

在C ++ 11中,可以使用初始化列表:

In C++11, you can use an initialiser list:

string second {first[0]};