最初の文字列からの単一の文字で2番目の文字列を初期化するよりエレガントな方法はありますか?例えば。文字列(size_t n、char c)コンストラクターに頼らずに?
string first = "foobar";
string second(string(1, first[0]));
あなたが言及するコンストラクターは、1つの文字から文字列を作成する方法であるため、これほど洗練された方法はありません。ただし、一時的なものを作成してコピー/移動する必要はありません。
string second(1, first[0]);
または、次の部分文字列から作成することもできますfirst
。
string second(first, 0, 1);
C ++ 11では、初期化子リストを使用できます。
string second {first[0]};
どうですか:
string ( );
string ( const string& str );
string ( const string& str, size_t pos, size_t n = npos );
string ( const char * s, size_t n );
string ( const char * s );
string ( size_t n, char c ); //<<--- this
すなわち
string second(1, first[0]);
上記は初期化の唯一のオプションであることに注意してください。
私はあなたに提案します:
string first = "foobar";
string second;
second = first[0];